Linq-to-sql EF4 - 从中​​生成列表

时间:2011-06-21 05:38:19

标签: .net entity-framework-4.1

我有以下EF

Education {
long id,
string name,
}

User {
long id
string name
...
}

UserEducation
{
long userId,
long educationId,
long rank
}

我想要一个linq-to-sql调用,它将返回如下结果: 用户名 教育作为教育清单1,教育2,教育3等

我可以使用

获得包含多个教育记录的结果
from u in users where u.userIsSomething.Equals(true)
join d in usereducation on u.id equals d.userid
join e in education on d.educationId equals e.Id
select new UserEd() {
  UserName = u.Name,
  Education =  <--- I end up with several unique education entries, I want to flatten into a list

所以请记录

等记录
Fred   AA in Culinary Arts
Fred   BS in Food Science
Fred   MBA

生成

佛瑞德 烹饪艺术学士,食品科学学士,工商管理硕士

我意识到我可以简单地循环记录,但我想把它变成一个声明。

没有找到类似的问题,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果您使用的是linq-to-sql或实体框架,则应该具有导航属性,因此您的手动连接是多余的。如果您没有导航属性,则表明您正在以错误的方式使用技术。重新定义模型以包含导航属性并尝试此操作(未经测试):

var query = from u in context.Users where u.userIsSomething.Equals(true)
            select new UserEd {
                UserName = u.Name,
                Education = from ue in u.UserEducations
                            group ue by ue.Rank into grouped
                            select new RankedEd {
                                grouped.Key,
                                grouped.Select(g => g.Education.Name) 
                            }
            });