Using custom dialect functions

In this recipe, we will show how you can add mappings for database functions, which are not available by default.

How to do it…

  1. Create a new class library project named CustomDialectExample.
  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 a new class named CustomMsSql2012Dialect using the following code:
    public class CustomMsSq2012Dialect:
      MsSql2012Dialect
    {
      public CustomMsSq2012Dialect()
      {
        RegisterFunction("AddDays",
          new SQLFunctionTemplate(
            NHibernateUtil.DateTime,
            "dateadd(day,?2,?1)"));
        RegisterFunction("AddHours",
          new SQLFunctionTemplate(
            NHibernateUtil.DateTime,
            "dateadd(hour,?2,?1)"));
        RegisterFunction("AddMinutes",
          new SQLFunctionTemplate(
            NHibernateUtil.DateTime,
            "dateadd(minute,?2,?1)"));
        RegisterFunction("AddSeconds",
          new SQLFunctionTemplate(
            NHibernateUtil.DateTime,
            "dateadd(second,?2,?1)"));
        RegisterFunction("AddMilliseconds",
          new SQLFunctionTemplate(
            NHibernateUtil.DateTime,
            "dateadd(millisecond,?2,?1)"));
      }
    }
  4. Use this dialect in your configuration, as described in Chapter 1, The Configuration and Schema.

How it works…

The dialect has the RegisterFunction method, but it is not public, as all dialects are tightly coupled to the RDBMS they represent. Thus, to register a custom function we create a custom dialect class.

We use the SQLFunctionTemplate class to register four of our custom functions. This class implements the ISQLFunction interface. This interface is responsible for rendering the function into SQL.

See also

  • Configuring NHibernate with hibernate.cfg.xml
  • Configuring NHibernate with .config file
  • Configuring NHibernate with code
  • Configuring NHibernate with Fluent NHibernate
  • Using custom functions in LINQ
..................Content has been hidden....................

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