EF Core 3.1 - 无法翻译 LINQ 表达式(左连接与 group by)

时间:2021-06-15 08:17:38

标签: c# entity-framework linq entity-framework-core

var query = await (from funnel in _readerBaseQuery
                        join lead in _readerContext.Leads on funnel.Id equals lead.SalesFunnelId into leadFunnelGroup
                        from leadFunnel in leadFunnelGroup.DefaultIfEmpty()
                        join leadProduct in _readerContext.LeadProducts on leadFunnel.Id equals leadProduct.LeadId into leadProductGroup
                        from product in leadProductGroup.DefaultIfEmpty()
                        group new { LeadId = leadFunnel.Id, TotalFirst = product.TotalFirst } by leadFunnel.SalesFunnelStageId into newGroup
                        select new { 
                            SalesFunnelStageId = (long)newGroup.Key, 
                            LeadsCount = newGroup.Select(x => x.LeadId).Count(),
                            LeadsValue = newGroup.Select(x => x.TotalFirst).Sum()
                        })
                        .ToListAsync();

我正在尝试使用 EF Core 和 LINQ 在我的 API/存储库层中按操作进行简单的分组,但它抛出如下错误:

The LINQ expression '(GroupByShaperExpression:
KeySelector: (l.SalesFunnelStageId), 
ElementSelector:new { 
    LeadId = (ProjectionBindingExpression: LeadId), 
    TotalFirst = (ProjectionBindingExpression: TotalFirst)
 }
)
.Select(x => x.LeadId)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

SQL 查询就像我在 MySQL 中尝试过的一样,它运行良好 Query executed in MySQL

 select l.SalesFunnelStageId, count(distinct l.Id) as LeadsCount, sum(lp.TotalFirst) as LeadsTotal
    from salesfunnels f
    left join leads l on l.SalesFunnelId = f.Id
    left join leadproducts lp on lp.LeadId = l.id
    group by l.SalesFunnelStageId

LINQ 查询方式或 C# 中的 group by 方式是否有问题?

1 个答案:

答案 0 :(得分:0)

您必须将分组投影更改为可翻译。不支持带有分组项目的 Select。 EF Core 5.x 之前也不支持不可空字段的 Count,并且可以由 Sum 模拟。

var query =
    from funnel in _readerBaseQuery
    join lead in _readerContext.Leads on funnel.Id equals lead.SalesFunnelId into leadFunnelGroup
    from leadFunnel in leadFunnelGroup.DefaultIfEmpty()
    join leadProduct in _readerContext.LeadProducts on leadFunnel.Id equals leadProduct.LeadId into leadProductGroup
    from product in leadProductGroup.DefaultIfEmpty()
    group new { leadFunnel, product } by leadFunnel.SalesFunnelStageId into newGroup
    select new { 
        SalesFunnelStageId = (long)newGroup.Key, 
        LeadsCount = newGroup.Sum(x => (int?)x.leadFunnel.LeadId != null : 1 : 0),
        LeadsValue = newGroup.Sum(x => x.product.TotalFirst)
    };