在Concat投影中使用Cast Projection

lal*_*ibi 5 nhibernate projection queryover

我有以下查询:

var result = _session.QueryOver<Entity>()
    .Where(e => e.Property == value)
    .SelectList(list => list
        .Select(f => Projections.Concat("prefix-", e.BigIntProperty)).WithAlias(() => alias.Whatever)
        ...
    )
    .TransformUsing(Transformers.AliasToBean<Model>())
    .Future<Model>();
Run Code Online (Sandbox Code Playgroud)

问题是Projections.Concat()只接受字符串,因为e.BigIntProperty不是,上面的代码不能编译.有没有办法转换e.BigIntProperty为字符串?

我尝试了类似下面的内容,它也不起作用:

.Select(f => Projections.Concat("prefix-", Projection.Cast(NHibernateUtil.String, e.BigIntProperty))).WithAlias(() => alias.Whatever)
Run Code Online (Sandbox Code Playgroud)

,因为Projections.Cast返回一个IProjection而不是一个字符串.

And*_*ker 4

Projections.Cast似乎非常有限,因为它不能接受任意Projections。幸运的是,您可以轻松创建自己的自定义投影,从而实现这一点:

public static class CustomProjections
{
    public static IProjection Concat(params IProjection[] projections)
    {
        return Projections.SqlFunction(
            "concat",
            NHibernateUtil.String,
            projections);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将能够CustomProjections像这样使用您的类:

var result = _session.QueryOver<Entity>()
    .Where(e => e.Property == value)
    .SelectList(list => list
        .Select(CustomProjections.Concat(
            Projections.Constant("prefix-"),
            Projections.Cast(
                NHibernateUtil.String,
                Projections.Property<Entity>(e => e.BigIntProperty))))
            .WithAlias(() => alias.Whatever)
        ...
    )
    .TransformUsing(Transformers.AliasToBean<Model>())
    .Future<Model>();
Run Code Online (Sandbox Code Playgroud)