NHibernate COALESCE问题

时间:2014-10-14 15:00:07

标签: c# nhibernate nhibernate-criteria queryover

我试图用NHibernate

表达以下SQL查询
DECLARE @date DATETIME = NULL;

SELECT 
    ER.Id
,   ER.DocumentDate
FROM 
    ExpenseReport ER
WHERE
    ER.PeriodFrom >= COALESCE(@date, ER.PeriodFrom)
OR ER.PeriodTo <= COALESCE(@date, ER.PeriodTo);

所以,在C#部分,我确实有以下类:

  • 表示实体:ExpenseReport
  • 我的搜索本身是一个单独的类

代码段:

// ----- Entity class.
public partial class ExpenseReport
{
    public Nullable<System.DateTime> PeriodFrom { get; set; }
    // many other properties
}

// ----- Search parameter class.
public class SearchParameters
{
    public Nullable<System.DateTime> DateFrom { get; set; } 
    // many other properties
}

因此,现在将搜索参数分配给IQueryOver<ExpenseReport>

var q = SessionProvider.QueryOver<ExpenseReport>();

现在我对NHibernate感到有点迷茫....我现在该怎么做?

q.And( /*** I AM STUCK HERE **/)

1 个答案:

答案 0 :(得分:4)

草稿代码应如下所示:

// left side
var left = Projections.Property<ExpenseReport>(ti => ti.PeriodFrom);
// right side
var right = Projections.SqlFunction("COALESCE"
        , NHibernateUtil.DateTime
        , Projections.Constant(search.DateFrom, NHibernateUtil.DateTime)
        , Projections.Property<ExpenseReport>(ti => ti.PeriodFrom)
    );
// the restriction using the GeProperty, taking two IProjections
var restriction = Restrictions.GeProperty(left, right);

// finally - our query get its WHERE
q.Where(restriction);

因此,我们首先创建两个预测。然后我们使用Restrictions实用程序集来创建>= (GeProperty)。最终的限制最终传递到WHERE子句......