我已经阅读了大量博客文章,并且尚未找到如何在两个表之间执行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
答案 0 :(得分:1)
我会写这个,远比join
和does 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 };