以下是简化后的代码
from oi in orderItems
group oiGrouped by ...
into orderItemsGroupedBySomething
select new
{
Key = orderItemsGroupedBySomething.Key,
Revenue = /*Here is some code that I want to extract to separate method, for example*/
orderItemsGroupedBySomething.Sum(x => x.UnitPrice * x.Quantity)
}
实际上我的情况更复杂。但我认为这无关紧要。我无法提取到orderItemsGroupedBySomething.Sum(x => x.UnitPrice * x.Quantity)
的简单方法计算,因为它不是EntityFramework的已知方法。我试着把它的表达式,但我得到错误"The LINQ expression node type 'Invoke' is not supported in LINQ to Entities."
我编译表达式之前使用它的查询,我认为因此我得到错误。我该如何解决这个问题?
我不知道你需要它有多通用,但像这样的东西应该工作:
void Main()
{
OrderItems.GroupBy(oi => oi.SomeProp).Select(GetExpression());
}
public Expression<Func<IGrouping<KeyType, OrderItem>, dynamic>> GetExpression()
{
return (ig) => new { Key = ig.Key, Revenue = ig.Sum(x => x.UnitPrice * x.Quantity) };
}
edit:在分组的情况下,我可能会返回Tuple而不是匿名类型。
我添加了返回表达式的方法
public Expression<Func<OrderItem, decimal>> GetExpression()
{
return x => x.UnitPrice*x.Quantity;
}
Then I try
from oi in orderItems
group oiGrouped by ...
into orderItemsGroupedBySomething
select new
{
Key = orderItemsGroupedBySomething.Key,
Revenue = orderItemsGroupedBySomething.Sum(GetExpression())
}
但是它不起作用,比如@LorentzVedeler的答案。因为orderItemsGroupedBySomething是igrouing类型的,没有Sum方法和表达式类型的参数。因此我尝试了
orderItemsGroupedBySomething.AsQueryable.Sum(GetExpression())
引起Internal .NET Framework Data Provider error 1025
。问题是我在linq中调用了GetExpression()方法。为了解决这个问题,我把表达式放到局部变量中。结果
var expression = GetExpression();
from oi in orderItems
group oiGrouped by ...
into orderItemsGroupedBySomething
select new
{
Key = orderItemsGroupedBySomething.Key,
Revenue = orderItemsGroupedBySomething.AsQueryable.Sum(expression)
}