Fetching records by date with only day part comparison using nhibernate

不想你离开。 提交于 2019-12-01 17:09:10

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 );
}

It depends on the LINQ provider. I'm not sure if NHibernate LINQ provider supports the item.SomeDateProperty.Date == x syntax and I'm doubtful it does. But, you can make your own extension method like so:

public static IQueryable<T> FilterByDate(this IQueryable<T> This, Expression<Func<T, DateTime>> getProperty, DateTime date)
{
  DateTime from = day.Date;
  DateTime to = day.Date.AddDays(1);
  return This.Where(x=> 
    Expression.And(
      Expression.GreaterThan(getProperty, Expression.Variable(from)),
      Expression.LessThan(getProperty, Expression.Variable(to)));

}

This is NOT going to build the way it is now - I was just trying to give you an idea of what to do.

You can then use it like so:

var result = repository.Table.FilterByDate(x=>x.MyDate, new DateTime(2012, 6,6));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!