组加入选择,逗号分隔

时间:2019-03-18 06:27:12

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

我在带有EF的.net Core 2.2中有一个类似下面的查询。

var data = context.Customer
                    .GroupJoin(context.Orders, c=> c.Id, o => o.CustoerId, (c, o) => new
                    {
                        customer = c,
                        orders= o
                    }).Select(s => new
                    {
                        s.customer.Name,
                        s.customer.Id,
                        AllOrdersRef = s.orders == null ? null : string.Join(", ", s.orders.Select(x => x.UniquRef))
                    });

显示错误

  

LINQ表达式'Count()'无法翻译,将在本地求值。

我想要的是AllOrdersRef中的逗号分隔值。我也不想用 ToList()。

2 个答案:

答案 0 :(得分:1)

您应该进行join查询,然后在 client 端处理它的结果:

var data = (from c in context.Customer
            join o in context.Orders on c.Id equals o.CustomerId into subs
            from sub in subs.DefaultIfEmpty()
            select new 
            {
                 c.Id,
                 c.Name,
                 UniquRef = sub == null ? null : sub.UniquRef
            }).ToList();

var result = data.GroupBy(x => new { x.Id, x.Name }).Select(x => new 
             {
                 x.Key.Id,
                 x.Key.Name, 
                 AllOrdersRef = (x.Count() == 1 && x.First().UniquRef == null) ? null
                                    : String.Join(", ", x.Select(y => y.UniquRef))
             });

答案 1 :(得分:0)

关于Sql Server(如果是您的DBMS),有两个主要函数对string输出进行group by串联,XML Path and String_Agg (from Sql Server 2017)在{{1}中不支持}。据我所知,其他DBMS也不支持它,因此您唯一的方法是将其强制转换为linq to sql之前的Enumerable
为此,您只需在string.Join之前致电ToList()

Select
相关问题