LINQ to Entities中聚合函数的表达式树

时间:2015-01-31 01:33:38

标签: c# linq entity-framework linq-to-entities aggregate-functions

我需要在LINQ to Entities查询之上动态替换聚合函数以在数据库中执行操作,同时不对我使用的函数进行硬编码,例如在查询中将Average()替换为Max()Min()

IQueryable<Order> orders = ordersRepository.GetAll();
var q = from o in orders
        group o by o.OrderDate into g
        select new
        {
            OrderDate = g.Key,
            AggregatedAmount = g.AsQueryable()
                                .Average(x => x.Amount)
        };

我坚持将Queryable.Average()翻译成一个表达式树,该表达式树可以放入查询中并成功转换为SQL。

1 个答案:

答案 0 :(得分:1)

g.Average(x => x.Amount)Queryable.Average(g, x => x.Amount)。我们想要替换Queryable.Average部分。像那样:

Expression<Func<IQueryable<Order>, Func<Order, double>>> aggregate = ...;

然后使用表达式:

AggregatedAmount = aggregate(g, x => x.Amount)

问题是你无法调用表达式。所以使用AsExpandable

var q = from o in orders.AsExpandable()
...
AggregatedAmount = aggregate.Compile()(g, x => x.Amount)

这会将aggregate内联到查询表达式中,以便EF甚至不知道它在那里。