Using in-built sql “Convert” function in nhibernate criteria

这一生的挚爱 提交于 2019-12-11 02:59:45

问题


I want to make use of the Convert function in SQL Server 2008 so I can search on a DateTime column.

The proposed SQL would look something like this:

SELECT (list of fields) FROM aTable
WHERE CONVERT(VARCHAR(25), theColumn) LIKE '%2009%'

Here is part of the criteria that tries to emulate the call to convert:

Projections.SqlFunction("CONVERT", 
  NHibernateUtil.String, 
  Projections.Constant("varchar(25)"), 
  Projections.Property(searchCol))

The search column would be dynamically selected so it cannot be hard coded in a query.

The problem is that when the SQL is generated by nhibernate, its passing in the data type as a string, when there shouldn't be any quotes around it.

So the generated sql looks like:

(convert(@p3, this_.theColumn) LIKE @p4

When it needs to be:

(convert(varchar(25), this_.theColumn) LIKE @p4

I am definitely sure the problem is with Projections.Constant("varchar(25)") but I do not know the correct projections syntax to make it work.


回答1:


If you could accept the CAST instead of CONVERT (And I am almost sure that you can), then there is more straightforward solution.

Instead of calling "SQL Server related" function, let's call the abstraction, which should be working on most DB Servers (based on supported NHibernate dilacts)

Projections.Cast(NHibernateUtil.String, Projections.Property(searchCol))

So the Restriction used in a WHERE clause could look like this:

Restrictions
    .Like (
        Projections.Cast(NHibernateUtil.String, Projections.Property(searchCol))
        , "2009"
        , MatchMode.Anywhere
    )

And the result generated by NHibernate, using the SQL Server dialect would be:

WHERE cast( this_.theColumn as NVARCHAR(255)) like @p1 ... @p1=N'%2009%'


来源:https://stackoverflow.com/questions/18875257/using-in-built-sql-convert-function-in-nhibernate-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!