在Nhibernate QueryOver中使用计算属性(未映射)

时间:2016-06-07 08:57:33

标签: c# sql linq nhibernate

我有一个表A,其中包含以下列:

AId - TargetId - IsActive

对应于此表,我有下面的类(带有额外的计算属性)和mapper:

public class A 
{
    public virtual long AId { get; set; }
    public virtual int TargetId { get; set; }
    public virtual int IsActive { get; set; }

    //calculated property, doesn't exist in the table
    public virtual bool IsClientSide
    {
        get { return ((this.TargetId & TargetEnum.ClientSide) != 0); }
    }
}
using NHibernate.Mapping.ByCode;
using NHibernate.Mapping.ByCode.Conformist;
using NHibernate.Type;
using ANamespace.A;

namespace mapping 
{
    public class AMap : ClassMapping<A> 
    {
        public AMap() 
        {
            this.Cache(x => { x.Usage(CacheUsage.NonstrictReadWrite); x.Region("LongTerm"); x.Include(CacheInclude.All); });
            this.Lazy(false);
            this.Mutable(true);
            this.DynamicUpdate(true);
            this.Id(x => x.AId, map => map.Generator(Generators.Native));
            this.Property(x => x.TargetId, map => { map.NotNullable(true); map.Type<EnumType<TargetEnum>>(); });
            this.Property(x => x.IsActive, map => map.NotNullable(true));
        }
    }
}

我没有映射这个IsClientSide属性,因为它不在表中。但是我想在我的查询中使用它,如下所示:

A aobject = null;
alist = session.QueryOver(() => aobject)

        .Where(a => a.IsClientSide)
        .And(tt => a.IsActive)
        ......

我找到了Hendry Luk&#34; Linq-ing计算属性&#34;发布但ILinqToHqlGenerator似乎过于复杂,无法使用这个小小的属性。

如何在我的mapper类中制定 IsClientSide 属性呢?

1 个答案:

答案 0 :(得分:4)

我们需要1) Formula 映射和2)bitwise operator

Property(x => x.IsClientSide, map =>
{
    map.Formula("(Target_ID & 1 <> 0)");
});

和属性应该由NHibernate分配

public virtual bool IsClientSide { get; protected set; }

现在我们可以在任何查询中使用IsClientSide ...