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?
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
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With