如何执行Linq to Entities Left Outer Join

时间:2010-06-24 20:52:11

标签: entity-framework linq-to-entities left-join

我已经阅读了大量博客文章,并且尚未找到如何在两个表之间执行LEFT OUTER JOIN的简单明了的示例。关于联接Join (SQL)的维基百科文章提供了这个简单的模型:

CREATE TABLE `employee` (
`LastName` varchar(25),
`DepartmentID` int(4),
UNIQUE KEY `LastName` (`LastName`)
);

CREATE TABLE `department` (
`DepartmentID` int(4),
`DepartmentName` varchar(25),
UNIQUE KEY `DepartmentID` (`DepartmentID`)
);

假设我们有一个EmployeeSet作为员工容器ObjectSet<Employee> EmployeeSet和一个DepartmentSet ObjectSet<Department> DepartmentSet。您将如何使用Linq执行以下查询?

SELECT LastName, DepartmentName
FROM employee e 
  LEFT JOIN department d 
    ON e.DepartmentID = d.DepartmentID

2 个答案:

答案 0 :(得分:1)

我会写这个,joindoes exactly the same thing更简单:

var q = from e in db.EmployeeSet
        select new 
        {
            LastName = e.LastName,
            DepartmentName = e.Department.DepartmentName
        };

答案 1 :(得分:0)

您需要使用DefaultIfEmpty方法:

var query =
    from e in db.EmployeeSet
    join d in db.DepartmentSet on e.DepartmentID equals d.DepartmentID into temp
    from d in temp.DefaultIfEmpty()
    select new { Employee = e, Department = d };