NHibernate COALESCE issue

久未见 提交于 2019-12-23 21:29:00

问题


I am trying to express the following SQL query with NHibernate

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);

So, in the C# part I do have the following classes:

  • for the entity : ExpenseReport
  • for my search itself a separate class

Code snippets:

// ----- 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
}

So, assigning now the search parameters to IQueryOver<ExpenseReport>

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

And I am a bit lost now with NHibernate .... How do I do it now?

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

回答1:


A drafted code should look like this:

// 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);

So, we firstly create two projections. Then we used the Restrictions utility set to create the >= (GeProperty). Resulting restriction is finally passed into WHERE clause...



来源:https://stackoverflow.com/questions/26364036/nhibernate-coalesce-issue

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