Fetching records by date with only day part comparison using nhibernate

前端 未结 3 1312
一生所求
一生所求 2021-01-18 06:51

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 IQueryabl         


        
相关标签:
3条回答
  • 2021-01-18 07:27

    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));
    
    0 讨论(0)
  • 2021-01-18 07:36

    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
    
    0 讨论(0)
  • 2021-01-18 07:42
    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 );
    }
    
    0 讨论(0)
提交回复
热议问题