EF核心Linq groupby并具有总计数-无法翻译,将在本地进行评估

时间:2018-12-11 18:32:54

标签: linq asp.net-core ef-core-2.0

在.net核心EF核心之后,Linq无法翻译,将在本地进行评估。你能给我个建议吗?

var temp1= (from so in context.OrderShippingOrders
            group so by so.OrderId into g
            where g.Count(x=> x.IsSent == true ) == g.Count()
            select new {
                        g.Key
                       }
           );

            query = (from o in context.Orders
                     join s in temp1
                     on o.Id equals s.Key
                     select o
                     );

LINQ表达式'在{from IGrouping 1[ECommerce.API.Models.Order]) where ([o].ShopId == __queryObj_ShopId_Value_0) join <>f__AnonymousType18 1 [ECommerce.API.Models]中,以{from order o in value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable 2 g in {from OrderShippingOrder so in value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable 1s in { .OrderShippingOrder])orderby [so] .OrderId asc,[so] .OrderId asc select [so] => GroupBy([so] .OrderId,[so])}其中({from OrderShippingOrder x in [g]其中([ x] .IsSent == True)选择[x] => Count()} == {[g] => Count()})选择新的<> f__AnonymousType18 1(Key = [g].Key)} on [o].Id equals [s].Key orderby EF.Property(?[o]?, "Id") asc select new AnonymousObject(new [] {Convert(EF.Property(?[o]?, "Id"), Object)}) => Skip(__p_1) => Take(__p_2) => Distinct()} on Property([o.OrderDetails], "OrderId") equals Convert([_o].GetValue(0), Nullable 1)'无法翻译,将在本地进行评估。

1 个答案:

答案 0 :(得分:3)

如果可能,请升级到EF Core 2.1(或2.2)以获得改进的LINQ GroupBy translation

  

在2.1版之前,在EF Core中,始终会在内存中评估GroupBy LINQ运算符。现在,在大多数情况下,我们支持将其转换为SQL GROUP BY子句。

在以前的EF Core版本中您无能为力。

升级后,为了获得SQL转换,必须将GroupBy查询修改为使用中间投影和条件Sum而不是条件Count,如下所示:

var temp1 = (from so in context.OrderShippingOrders
             group new { SendCount = so.IsSent ? 1 : 0 } by so.OrderId into g
             where g.Sum(x => x.SendCount) == g.Count()
             select new
             {
                 g.Key
             }
);

(不幸的是,较自然的group sog.Sum(x => x.IsSent ? 1 : 0)不会翻译,这就是为什么我们需要group new { SendCount = so.IsSent ? 1 : 0 }g.Sum(x => x.SendCount)的原因)


P.S。如果您具有从OrderOrderShippingOrder的集合导航属性(类似public ICollection<OrderShippingOrder> Shipping { get; set; }),则可以避免所有这些GroupBy的复杂性,只需使用:

var query = context.Orders
    .Where(o => o.Shipping.Count(so => so.IsSent) == o.Shipping.Count());