Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching records by date with only day part comparison using nhibernate

I would like to fetch all records from particular day, no matter what time is associated with those records. So far I have method like this:

public IQueryable<Record> QueryByDay(DateTime day)
{
    DateTime from = day.Date;
    DateTime to = day.Date.AddDays(1);

    return repository.Table
        .Where(t => t.MyDate >= from && t.MyDate < to);
    }

But in linq-to-object we can do (assuming Table is now some collection):

public IEnumerable<Record> QueryByDay(DateTime day)
{
    return repository.Table
        .Where(t => t.MyDate.Date == day.Date);
}

Which is obviously more readable and feels more clean. I was wondering if there is better way to write the first method using database storage and nhibernate?

like image 457
0lukasz0 Avatar asked Jun 06 '12 18:06

0lukasz0


2 Answers

As said in the comments, your LINQ query works fine with NH 3.3.

In earlier releases, you can use HQL:

return session.CreateQuery("from MyClass where date(MyDate) = :day")
              .SetParameter("day", day.Date)
              .List<MyClass>(); //executes

You can also use the date function from Criteria, via SqlFunction. This is more convoluted, but allows building more dynamic queries:

return session.CreateCriteria<Foo>()
              .Add(Restrictions.Eq(
                       Projections.SqlFunction("date",
                                               NHibernateUtil.Date,
                                               Projections.Property("MyDate")),
                       day.Date))
                .List<MyClass>(); //executes
like image 112
Diego Mijelshon Avatar answered Nov 14 '22 23:11

Diego Mijelshon


public IEnumerable<Record> QueryByDay(DateTime day)
{
    return repository.Table
        .Where(t => t.MyDate.Day == day.Day && t.MyDate.Month == day.Month && t.MyDate.Year == day.Year );
}
like image 20
Ivo Avatar answered Nov 14 '22 23:11

Ivo