NHibernate查询根据列差异进行过滤

时间:2014-06-19 09:35:19

标签: c# asp.net nhibernate

以下是约会模型的快照:

public class Appointment
{
    public virtual DateTime? InTime {get; set;}
    public virtual DateTime? OutTime {get; set;}
}

我希望所有约会的持续时间少于2分钟。类似的东西:

var twoMinutes = new TimeSpan(0, 0, 2, 0);
var query =
            Repository.QueryOver<DomainModel.Models.Appointment>()
                .Where(a => a.OutTime.Value - a.InTime.Value < twoMinutes);
return query.List();

例外:

变量&#39; a&#39;类型&#39; DomainModel.Models.Appointment&#39;引用范围&#39;&#39;,但未定义

当我使用QueryOver()尝试这个时,我收到一个错误。我如何使用ICriteria或nHibernate中的任何其他方式执行此操作?

1 个答案:

答案 0 :(得分:0)

此处的解决方案正如我在评论中已经提到的那样是将该比较移到DB中。这应该用(据我所知)进行投影:

// two minutes
var twoMinutes = 2d;

// the query
var query = Repository.QueryOver<DomainModel.Models.Appointment>();

// the projection using DATEDIFF
var projection = Projections
    .SqlProjection("DATEDIFF(mi, {alias}.InTime ,{alias}.outTime) as difference"
               , new[] {"difference"}
               , new[] {NHibernateUtil.Double});

现在我们可以在查询中使用它:

query.Where(Restrictions.Ge(projection, twoMinutes));

检查

  

DATEDIFF(日期部分,开始日期,结束日期)

这意味着要获得正数,第一个arg必须更旧......

注意:QueryOver引擎将某些内容正确转换为适当的SQL,但这不是......