考虑以下 QueryOver(四分之一和中心是传入的变量):

QueryOver.Of<Activity>()
        .Where(Restrictions.On<Activity>(a => a.StartDate).IsBetween(quarter.StartDate).And(quarter.EndDate) ||
               Restrictions.On<Activity>(a => a.EndDate).IsBetween(quarter.StartDate).And(quarter.EndDate) ||
               Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate)))  //TODO: Refactor this to remove magic strings
        .And(a => a.Centre == centre)
        .OrderBy(a => a.Title).Asc;

此查询完美运行,但我想更改以下限制以删除魔术字符串:
Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate))

以下是实体(为简洁起见剪下):
public class Quarter
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

}

public class Activity
{
    public string Title { get; set; }
    public Centre Centre { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

}

public class Centre
{
    public string Name { get; set; }
}

那么使用新的 QueryOver 扩展的类型安全方法是什么,它可以让我删除这些魔法字符串?

最佳答案

这就是你想要的:

Restrictions.And(
    Restrictions.Lt(Projections.Property<Activity>(x => x.StartDate),
                    quarter.StartDate),
    Restrictions.Gt(Projections.Property<Activity>(x => x.EndDate),
                    quarter.EndDate)))

旁注:属性名称不是魔术字符串。

关于nhibernate - 使用 NHibernate QueryOver,如何在日期之间添加类型安全限制,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6212358/

10-15 21:21