在我的申请中,公司可以有很多员工,每个员工可能有多个电子邮件地址。
数据库模式将表格关联起来:
公司 - > 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"
...
我知道这段代码是错的,我想我错过了一个小组,但它说明了这一点。我不确定语法。这甚至可能吗?谢谢你的帮助。
答案 0 :(得分: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())
}
)
答案 1 :(得分:5)
实际上很难在纯Linq to SQL(或实体框架,无论你使用哪一个)中执行此操作,因为SQL Server本身没有任何可以生成逗号分隔列表的聚合运算符,所以它没有将整个语句转换为单个查询的方法。我可以给你一个“单一陈述”Linq to 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)
};