簡單的解決方案 - 應該像這樣工作:
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方面的方式...... –