Using the NHibernate QueryOver, how can you add a type-safe restrictions between dates
Considering the following QueryOver
(quarter and centre are variables passed in):
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开发者_如何学Go.Centre == centre)
.OrderBy(a => a.Title).Asc;
This query works perfectly, but I'd like to change the following restriction to remove the magic strings:
Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate))
Here are the entities (snipped for brevity):
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; }
}
So what is the type-safe way using the new QueryOver extensions that will enable me to remove these magic strings?
This is what you want:
Restrictions.And(
Restrictions.Lt(Projections.Property<Activity>(x => x.StartDate),
quarter.StartDate),
Restrictions.Gt(Projections.Property<Activity>(x => x.EndDate),
quarter.EndDate)))
Sidenote: property names are not magic strings.
精彩评论