通过获取最新记录只使用一天的一部分NHibernate的比较 [英] Fetching records by date with only day part comparison using nhibernate

查看:144
本文介绍了通过获取最新记录只使用一天的一部分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);
    }



但在LINQ到对象,我们可以做(假设表是现在的一些集合):

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



这显然是更具可读性,感觉更干净。我不知道是否有更好的方式来写利用数据库​​存储和NHibernate的第一个方法是什么?

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?

推荐答案

由于在评论中说, 。您的LINQ查询工作正常与NH 3.3

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

在早期版本中,你可以使用HQL:

In earlier releases, you can use HQL:

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

您也可以使用日期从标准功能,通过SqlFunction。这是比较绕口,但允许建设更多的动态查询:

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

这篇关于通过获取最新记录只使用一天的一部分NHibernate的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆