Using SQL CONVERT function through nHibernate Criterion

自闭症网瘾萝莉.ら 提交于 2019-11-28 13:58:23
Radim Köhler

If the setting 104 is not essential, we can get a quick solution: use CAST instead of CONVERT. This SQL Function is built-in in the NHibernate dialects:

Projections.Cast(NHibernateUtil.DateTime
               ,Projections.Property(propNames[orderByColumn]))

If the setting 104 is important we can create our own Dialect, register the CONVERT function, and use it from then ... forever

Here Andrew Whitaker nicely shows how to

Based on Radim Köhler's answer, here is what I did to fix the problem:

Created a wrapper class to allow me to register the convert function and avoid the dialect exception described in my question:

public class MyDialect : MsSql2008Dialect
{
    public MyDialect()
    {
        RegisterFunction("ConvertDate", 
               new SQLFunctionTemplate(NHibernateUtil.Class, 
                                        "convert(datetime, ?1, 103)"));
    }
}

Created a custom projection class to allow me call the new function as a projection in its own right:

public static class MyProjections
{
    public static IProjection ConvertDate(params IProjection[] projections)
    {
        return Projections.SqlFunction("ConvertDate", 
                            NHibernateUtil.DateTime, projections);
    }
}

Then I check the data type that the string in column represents, then call the ConvertDate method if it is a date

 if (propTypes[orderByColumn] == typeof(DateTime))
 {
       criteria.AddOrder(orderIsDesc
           ? Order.Desc(MyProjections.ConvertDate(
                               Projections.Property(propNames[orderByColumn])))
           : Order.Asc(MyProjections.ConvertDate(
                               Projections.Property(propNames[orderByColumn]))));
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!