Using custom functions in LINQ

In this recipe, we will show you how to map database functions and stored procedures to LINQ functions.

Getting ready

Complete the previous recipe, Using custom dialect functions.

How to do it…

  1. Create a new class library project named CustomLinqGenearatorExample.
  2. Install the NHibernate and log4net packages using the NuGet Package Manager Console by executing the following command:
    Install-Package NHibernate
    Install-Package log4net
    
  3. Create the SqlFunctions class using the following code:
    public static class SqlFunctions
    {
      [LinqExtensionMethod]
      public static DateTime AddDays(DateTime dt, int d)
      {
        return dt.AddDays(d);
      }
    
      [LinqExtensionMethod]
      public static DateTime AddHours(DateTime dt, int h)
      {
        return dt.AddHours(h);
      }
    
      [LinqExtensionMethod]
      public static DateTime AddMinutes(DateTime dt, int m)
      {
        return dt.AddMinutes(m);
      }
    
      [LinqExtensionMethod]
      public static DateTime AddSeconds(DateTime dt, int s)
      {
        return dt.AddSeconds(s);
      }
    
      [LinqExtensionMethod]
      public static DateTime AddMilliseconds(
        DateTime dt, 
        int ms)
      {
        return dt.AddMilliseconds(ms);
      }
    }

How it works…

The LINQ provider will scan all methods inside the Linq expression for the [LinqExtensionMethod] attribute. For each of these methods, it will call the default LINQ to the HQL generator, simply replacing a call to the method with a call to the corresponding SQL function name. By default, the function name will be the same as the method name, but you can specify it using the constructor argument to the [LinqExtensionMethod] attribute.

See also

  • Using custom dialect functions
  • Extending the LINQ provider
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.231