Using NHibernate QueryOver, how can you add type constraints between dates

Given the following QueryOver(quarter and center are passed in by variables):

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;

This query works fine, but I would like to change the following restriction to remove the magic lines:

Restrictions.And(Restrictions.Lt("StartDate", quarter.StartDate), Restrictions.Gt("EndDate", quarter.EndDate))

Here are the entities (abbreviated 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 a safe type using the new QueryOver extensions that will allow me to remove these magic strings?

+3
source share
1 answer

Is this 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.

+6
source

All Articles