Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate and operator overloading

Tags:

c#

nhibernate

public class Version
{
    public byte Major { get; set; }
    public byte Minor { get; set; }
    public short Build { get; set; }
    public int Revision { get; set; }

    private long NumVersion
    {
        //get {}
        //set {}
        //Some logic that make Int64 number that represents this verion
    }
}

Suppose I want to be able to write queries like

Where<Product>(t=>t.Version > new Version(1,2,0,0))

In Product table I store only Int64 NumVersion field, so Version property is mapped as component, and currently I query it like Where<Product>(t=>t.Version.NumVersion > new Version(1,2,0,0).NumVersion)

In C# I can 1. Overload comparison operators, 2. Make it implicitly casted to long like:

public static implicit operator long(Version v)
{
    return v.NumVersion;
}

This will allow me to compare Version objects, but how to make NHibernate understand this and generate proper SQL ?

like image 249
Alex Burtsev Avatar asked Jul 22 '11 11:07

Alex Burtsev


2 Answers

It is impossible. You will either have to explicitly write comparisons for each Version component or filter on the client side.

like image 151
Anton Gogolev Avatar answered Sep 28 '22 12:09

Anton Gogolev


Maybe:

class p
{
    private p() { }

    public static p Version { get { return new p(); } }

    public static Expression<Func<Product, bool>> operator >(p left, Version version)
    {
        return product => product.Version.NumVersion > version.NumVersion;
    }
    ...
}


Where<Product>(p.Version > new Version(1,2,0,0))
like image 36
Firo Avatar answered Sep 28 '22 13:09

Firo