1

所以我从一个人表中选择,我需要选择这个人所在的组的组 ID。我该怎么做。

到目前为止,我有:

var p = (from p in Context.Person
         join g in Context.Group
         on p.PersonId equals g.PersonId
         select new
         {
             Name = p.Name,
             Age  = p.Age,
             groupIds = ?????
         }

所以在组表中它将是一个主键,GroupId所以PersonId我需要选择所有组 ID。如何才能做到这一点?

4

2 回答 2

6

你想要一个GroupJoin而不是一个Join. 不同之处在于,它不是将所有相关项扁平化为对列表,而是将所有连接项分组为一个序列:

var query = from p in Context.Person
            join g in Context.Group
            on p.PersonId equals g.PersonId into groups
            select new
            {
                Name = p.Name,
                Age  = p.Age,
                groupIds = groups.Select(g => g.GroupId),
            };

使用查询语法,将into关键字与 a 结合使用join将导致 aGroupJoin而不是 a Join

于 2013-07-03T15:15:57.493 回答
2

我在 SO 的编辑器上编码。如果我理解正确,您需要 Person 的组。否则请纠正我。

 var p = from p in Context.Person         
     select new
     {
         Name = p.Name,
         Age  = p.Age,
         groups = from g in Context.Group
                  where p.PersonId == g.PersonId
                  select g.GroupId
     };
于 2013-07-03T14:33:03.543 回答