Linq外连接多个表到多个表

时间:2017-10-25 15:33:14

标签: c# entity-framework linq

我有以下结构

团队> - 会员资格 - <员工

成员资格是一个多对多关系表,其中包含额外字段StartDate和EndDate,根据此示例设置:Create code first, many to many, with additional fields in association table

我想要完成的是在一个Linq查询中获取所有团队(左外连接)和Employees(左/右外连接),基本上会产生一个包含团队的大列表(和耦合)员工(如果有的话)和员工(如果有员工的话)。

这可能吗?

我试图通过以下方式做到这一点,但没有完全实现目标:

var queryable = (from t in Context.Teams
                    join m in Context.Membership on t.Id equals m.TeamId into tm
                    from result in tm.DefaultIfEmpty()
                    join e in Context.Employees on result.EmployeeId equals e.Id into em
                    from r in em.DefaultIfEmpty()
                    select new { TeamLinq = t, MembershipLinq = result }).ToList();

var q = (from m in Context.Membership
            join t in Context.Teams on m.TeamId equals t.Id into tm
            join e in Context.Employees on m.EmployeeId equals e.Id into em
            from result in tm.DefaultIfEmpty()
            from result2 in em.DefaultIfEmpty()
            select new { Foo = result, Bar = result2 }).ToList();

但没有得到我之后的目标。

在简单的SQL中,我会像

一样编写它
select * from Teams t left outer join Membership m on t.Id = m.TeamId
right outer join Employees e on e.Id = m.EmployeeId

1 个答案:

答案 0 :(得分:0)

这应该有效

var queryable = 
   (from t in Context.Teams
    from m in Context.Membership.Where(r => t.Id == r.TeamId).DefaultIfEmpty()
    from e in Context.Employees.Where(r => m != null && m.EmployeeId == r.Id).DefaultIfEmpty()
    select new { Team = t, Membership = m }).ToList();

它适用于Linq-to-objects。

    var list = (from t in teams
                from m in mtm.Where(r => t.Id == r.TeamId).DefaultIfEmpty()
                from e in emps.Where(r => m != null && m.EmployeeId == r.Id).DefaultIfEmpty()
                select new { t = t.Id, e = e != null ? e.Id : -1 }).ToList();

    list.ForEach(x => Console.WriteLine("Team: {0}; Emp: {1}", x.t, x.e)    )   ;
  

团队:1; Emp:-1
  球队:2; Emp:-1
  球队:3; Emp:-1
  球队:4; Emp:2
  球队:4; Emp:3
  球队:4; Emp:4
  球队:5; Emp:2
  球队:5; Emp:4
  球队:6; Emp:2
  球队:7; Emp:2
  球队:8; Emp:-1
  球队:9; Emp:-1
  团队:10; Emp:-1
  球队:11; Emp:-1
  球队:12; Emp:-1