Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a calculated property (not mapped) in Nhibernate QueryOver

I have a table A, which has following columns:

AId - TargetId - IsActive

Corresponding to this table, I have below class (with an additional calculated property) and 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));
        }
    }
}

I am not mapping this IsClientSide property, because it is not in the table. But I want to use it on my query like below:

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

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

I have found Hendry Luk's "Linq-ing Calculated Properties" post but ILinqToHqlGenerator seemed over-complicated to use this tiny property.

How can I formulate IsClientSide property in my mapper class, instead?

like image 760
emre Avatar asked Jun 07 '16 08:06

emre


1 Answers

We would need 1) Formula mapping and 2) bitwise operator

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

and property should be assignable by NHibernate

public virtual bool IsClientSide { get; protected set; }

And now we can use IsClientSide in any query...

like image 162
Radim Köhler Avatar answered Oct 03 '22 03:10

Radim Köhler