【问题标题】:apply linq filter converting expressions应用 linq 过滤器转换表达式
【发布时间】:2014-07-31 08:32:13
【问题描述】:

我有一个不错的 Linq 挑战。我想使用 FilterFunction 过滤日期上的一些数据。它应该像这样工作:

ApplyDateFilterEx(query,null, DateTime.Today, s => s.CreatedDate);

应该过滤查询,以便返回今天之前的所有“货件”。查询对象属于 IQueryable,整个查询应由 EF5 评估,因此应转换为 SQL。

这是我目前所拥有的(不编译):

private static IQueryable<Shipment> ApplyDateFilterEx(IQueryable<Shipment> query, DateTime? minDate, DateTime? maxDate, Expression<Func<Shipment, DateTime?>> dateMember)
    {
        if (minDate != null)
        {
            //convert func to expression so EF understands
            Expression<Func<Shipment, bool>> where = x => minDate <= dateMember(x);
            query = query.Where(where);
        }
        if (maxDate != null)
        {
            Expression<Func<Shipment, bool>> where = x => dateMember(x) <= maxDate;
            query = query.Where(where);
        }

        return query;
    }

你可以看到我想转换表达式 s=>DateTime? to s=> 要评估的布尔值。我怎样才能让它工作?

感谢您的阅读。 马丁

UDPATE: 我最终得到了这个(感谢 rdvanbuuren)

 var predicate = Expression.Lambda<Func<Shipment, bool>>(
                    Expression.GreaterThanOrEqual(
                        selector.Body,
                        Expression.Constant(dateFilter.MinDate, typeof (DateTime?))
                        ), selector.Parameters);

【问题讨论】:

    标签: linq linq-to-entities entity-framework-5


    【解决方案1】:

    看看 How to implement method with expression parameter c#

    我认为这正是您需要的,但使用 Expression.GreaterThanOrEqual 或 Expression.LessThanOrEqual。祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多