简单的解决方案 - 应该像这样工作:
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的上下的解决方案 - 的情况下,我们想使用该功能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
我是如此集中在NHibernate的东西*(期待'HOUR(列)'是一个函数)* ...你的SQL-ish方式选择HOUR当然是DB方面的方式...... –