Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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?

like image 287
andypike Avatar asked Feb 24 '23 00:02

andypike


1 Answers

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.

like image 190
Diego Mijelshon Avatar answered Feb 26 '23 13:02

Diego Mijelshon