【问题标题】:Group Join Select With Comma Separated以逗号分隔的组加入选择
【发布时间】:2019-03-18 06:27:11
【问题描述】:

我在带有 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()。

【问题讨论】:

  • 你确定这是你得到错误的地方吗?这里没有.Count
  • 我认为string.Join 不会在IQuerable<T> 中使用,您在DbSet<Customer>DbSet<Orders> 上使用linq,这就是为什么。可能你也有一些例外
  • 我相信你在“c.customer.Id”后面会出错,因为你没有逗号。
  • 你到底为什么要将UniqueRefs字符串连接成一个字符串?

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


【解决方案1】:

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

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))
             });

【讨论】:

  • 我认为 OP 不希望 .ToList() 在他/她期望查询返回 IQuerable<T> 的地方。
  • @er-sho, String.Join 无法翻译成SQL,所以IQuerable<T> 也无法实现,只有IEnumerable<T>
  • @SlavaUtesinov,我在那里执行了加入。但问题是我不希望它通过使用 ToList() 在本地进行评估。顺便谢谢你的回答。
【解决方案2】:

关于 Sql Server(如果它是您的 DBMS),有两个主要函数在 group by 输出上执行 string 连接,XML Path and String_Agg (from Sql Server 2017)linq to sql 中不支持这些函数。据我所知,其他 DBMS 也不支持它,因此您唯一的方法就是在 string.Join 之前将其转换为 Enumerable
为此,您只需要在Select 之前调用ToList()

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

【讨论】:

    猜你喜欢
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2016-04-02
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多