In this recipe, we will show how you can add mappings for database functions, which are not available by default.
CustomDialectExample
.NHibernate
and log4net
packages using the NuGet Package Manager Console by executing the following command:Install-Package NHibernate Install-Package log4net
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)")); } }
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.
3.16.69.199