Linq查询子查询为逗号分隔值

Kei*_*ith 6 linq subquery delimited

在我的应用程序中,公司可以拥有许多员工,每个员工可能拥有多个电子邮件地址.

数据库模式将表格关联如下:

公司 - > CompanyEmployeeXref - >员工 - > EmployeeAddressXref - >电子邮件

我正在使用Entity Framework,我想创建一个LINQ查询,该查询返回公司的名称以及它的员工电子邮件地址的逗号分隔列表.这是我正在尝试的查询:


from c in Company
join ex in CompanyEmployeeXref on c.Id equals ex.CompanyId
join e in Employee on ex.EmployeeId equals e.Id
join ax in EmployeeAddressXref on e.Id equals ax.EmployeeId
join a in Address on ax.AddressId equals a.Id
select new {
              c.Name,
              a.Email.Aggregate(x=>x + ",")
           }


Desired Output:

"Company1", "a@company1.com,b@company1.com,c@company1.com"

"Company2", "a@company2.com,b@company2.com,c@company2.com"

...

我知道这段代码是错的,我想我错过了一个小组,但它说明了这一点.我不确定语法.这甚至可能吗?谢谢你的帮助.

Kei*_*ith 7

现在我解决了这个问题:


from c in Company
join ex in CompanyEmployeeXref on c.Id equals ex.CompanyId
join e in Employee on ex.EmployeeId equals e.Id
join ax in EmployeeAddressXref on e.Id equals ax.EmployeeId
join a in Address on ax.AddressId equals a.Id
group a.Email by new {c.Name} into g
select new {
                Company=g.Key.Name,
                Email=g.Select(e=>e).Distinct()
            }
).ToList()
.Select(l=> 
           new {
                    l.Name,
                    Email=string.Join(",", l.Email.ToArray())
                }
        )



Aar*_*ght 5

实际上很难在纯Linq到SQL(或实体框架,无论你使用哪一个)中执行此操作,因为SQL Server本身没有任何可以生成逗号分隔列表的聚合运算符,因此它无法转换将整个语句转换为单个查询.我可以给你一个"单一陈述"Linq到SQL的答案,但它实际上不会给你很好的表现,而且我不确定它在EF中是否会起作用.

如果您只是进行常规连接,实现结果,然后使用Linq to Objects进行连接,那会更加丑陋但更好!

var rows =
    (from c in Company
     join ex in CompanyEmployeeXref on c.Id equals ex.CompanyId
     join e in Employee on ex.EmployeeId equals e.Id
     join ax in EmployeeAddressXref on e.Id equals ax.EmployeeId
     join a in Address on ax.AddressId equals a.Id
     select new 
     {
         c.Name,
         a.Email
     }).AsEnumerable();

var emails =
    from r in rows
    group r by r.Name into g
    select new
    {
        Name = g.Key,
        Emails = g.Aggregate((x, y) => x + "," + y)
    };
Run Code Online (Sandbox Code Playgroud)