Lesser-Known NHibernate Features: LINQ Extensions

With NHibernate, you are not bound by the out-of-the box methods that LINQ provides, and their default translations to SQL. I already mentioned that you can add your own extension methods, with minimum work:

public static class StringExtensions

{

    [LinqExtensionMethod("FREETEXT")]

    public static Boolean Freetext(this String propertyName, String value)

    {

        return (propertyName.ToUpper().Contains(value.ToUpper()));

    }

}

For this example, I am creating an extension for the FREETEXT T-SQL function, which is one of the ways by which we can do full-text searching. All it takes is the LinqExtensionMethodAttribute applied to a method, with the name for the database function (can be different from the method name), and that’s it! NHibernate will try to match the parameters:

   1: var result = session.Query<MyEntity>().Where(x => x.Name.Freetext("something") == true).ToList();

Yes… Entity Framework let’s you do this… kind of… only for some functions!

Addendum

As Paulo Morgado (@paulomorgado) pointed out, line “propertyName.ToUpper().Contains(value.ToUpper())” should really be “propertyName.IndexOf(value, StringComparison.IgnoreCase)“, because it avoids string allocations and in general is much better.

Thanks, Paulo! 😉

Published by

Ricardo Peres

Tech Lead at RedLight Software.

2 thoughts on “Lesser-Known NHibernate Features: LINQ Extensions”

  1. I have to do additional one more things for Oracle environment.
    Register Custom UDF in custom dialect file and
    mention the custom UDF.

    public class MyDialect : Oracle10gDialect
    {
    public MyDialect()
    {
    RegisterFunction(“customUDF”, new StandardSQLFunction(“customUDF”, NHibernateUtil.Int32));
    }
    }
    And mention it Fluent Configuration
    as
    .Dialect()

Leave a Reply

Your email address will not be published. Required fields are marked *