[Prev] Thread [Next]  |  [Prev] Date [Next]

[nhusers] IUserType with LINQ in where clause implementing BuildHql juanita Wed Feb 08 09:01:13 2012

I have implemented support for a custom user type in my domain model,
but struggle with supporting it in a LINQ where clause.

For the sake of simplicity, say that the database contains a COLOR
column where a color code is stored as RRGGBB in hex (e.g. FF00FF).
This column is mapped to a custom user type implementing IUserType
with three properties Red,Green,Blue, all integers.
Selecting, updating and inserting data all works fine. There are
plenty of examples for doing this.

However, what I am struggling with is implementing proper support for
using this type as part of Linq in a where clause. When trying to
lookup an item based on its color, then the linq query would need to
be something like this:

session.Query<Item>.Where( i => i.Color.Red == 255 && i.Color.Green==0
&& i.Color.Blue==255)

With just the IUserType implementation, the LINQ query will throw an
error. I have researched the matter and found recommendations to also
implement a HqlGenerator, specifically its BuildHql method. Some more
work is needed to get it registered and activated through subclassing
DefaultLinqToHqlGeneratorsRegistry and adding it as a property to the
NH configuration.

Here is what I have implemented so far:
    public class ColorHqlGenerator : BaseHqlGeneratorForProperty
        public ColorHqlGenerator()
            SupportedProperties = new[]
                ReflectionHelper.GetProperty((Color x) => x.Red),
                ReflectionHelper.GetProperty((Color x) => x.Green),
                ReflectionHelper.GetProperty((Color x) => x.Blue)

        public override HqlTreeNode BuildHql(MemberInfo member,
Expression expression, HqlTreeBuilder treeBuilder,
IHqlExpressionVisitor visitor)
            .... now what .... ???
The issue is with implementing the BuildHql method. I have pretty much
no idea what would need to be done here to have NHibernate finally
execute a SQL statement with ... where color='FF00FF'.

Note that merging the three where parts for the individual properties
(red, green, blue) into a single SQL where is highly desirable so that
the database can make use of an index on the column.
I understand that an edge case would be if the query had values only
for 2 or 1 of the color constituents. While this will not actually
happen in my case, an acceptable solution would be to assume the
missing constituents as 0.

What I am confused about in the few other examples I have seen is that
the HqlGenerator seems to make no use of the IUserType's methods to
convert between database and object representation at all.

Any help would be highly appreciated.

You received this message because you are subscribed to the Google Groups 
"nhusers" group.
To post to this group, send email to [EMAIL PROTECTED]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at