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! ;-)