简单的解决方案 - 应该像这样工作:
var hourProjection = Projections
.SqlProjection(" DATEPART(HOUR,field) as hour " // the left side of the expression
, new[] {"hour"} // alias
, new IType[] {NHibernateUtil.Int32}); // type is int
criteria.Add(Expression.Eq(hourProjection, myValue)); // myValue = 10
检查:How to compare datepart Month using Nhibernate Criteria?
NHibernate-ish 解决方案 - 如果我们想广泛使用该函数 HOUR,我们可以扩展 Dialect 及其定义:
public class CustomMsSql2012Dialect : MsSql2012Dialect
{
public CustomMsSql2012Dialect()
{
RegisterFunction("HOUR",
new SQLFunctionTemplate(NHibernateUtil.Class, "DATEPART(HOUR,?1)"));
}
}
并将其注入配置:
<property name="dialect">MyLib.CustomMsSql2012Dialect,MyLib</property>
然后像这样消费它:
var hourFunctionProjection = Projections
.SqlFunction("HOUR", NHibernateUtil.Int32, Projections.Property("Field"));
restrictions.Add(Restrictions.Eq(hourFunctionProjection, 10));
检查:Using SQL CONVERT function through nHibernate Criterion