选择具有多对多关系的对象集合的对象

时间:2015-04-22 15:49:20

标签: c# linq entity-framework

我有三个表:AthletesTeamsTeam_AthletesTeam_Athletes以多对多关系连接其他两个表。我正在做的是查询数据库以返回运动员和一组团队的对象。我目前正在执行以下两个查询:

   var query = (from a in db.Athletes
                join ta in db.Team_Athletes on a.Id equals ta.AthleteId
                join t in db.Teams on ta.TeamId equals t.Id
                where t.OrganizationId == organizationId 
                orderby a.LastName, a.FirstName
                select new
                {
                    Athlete = a,
                    Team = t
                }).ToArray();

   var result = from i in query
                group i by i.Athlete into g
                select new 
                {
                    Athlete = g.First().Athlete,
                    Teams = g.Select(i => i.Team).ToArray()
                };

如果可能的话,我想知道如何将查询组合在一起,但我无法想出任何有效的方法。想法?

1 个答案:

答案 0 :(得分:1)

为什么不使用:

var query = from a in db.Athletes
            join ta in db.Team_Athletes on a.Id equals ta.AthleteId
            join t in db.Teams on ta.TeamId equals t.Id
            where t.OrganizationId == organizationId 
            orderby a.LastName, a.FirstName
            group t by a into g
            select new { Athlete = g.Key, Teams = g };

然后你可以遍历结果,如下所示:

foreach (var entry in query)
{
    Console.WriteLine("Athlete: {0}", entry.Athlete);
    foreach (Team t in entry.Teams)
    {
        Console.WriteLine("Team: {0}", t);
    }
}