如何执行 Linq to Entites 左外连接

发布于 2024-09-06 18:45:16 字数 764 浏览 8 评论 0原文

我已经阅读了大量博客文章,但尚未找到如何在两个表之间执行 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; EmployeeSet 和 DepartmentSet ObjectSet部门集。您将如何使用 Linq 执行以下查询?

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

I have read plenty of blog posts and have yet to find a clear and simple example of how to perform a LEFT OUTER JOIN between two tables. The Wikipedia article on joins Join (SQL) provides this simple model:

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`)
);

Assume we had a EmployeeSet as an employee container ObjectSet<Employee> EmployeeSet and a DepartmentSet ObjectSet<Department> DepartmentSet. How would you perform the following query using Linq?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仙女山的月亮 2024-09-13 18:45:16

我会写这个,它比 join做同样的事情

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

I would write this, which is far simpler than join and does exactly the same thing:

var q = from e in db.EmployeeSet
        select new 
        {
            LastName = e.LastName,
            DepartmentName = e.Department.DepartmentName
        };
杀お生予夺 2024-09-13 18:45:16

您需要使用 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 };

You need to use the DefaultIfEmpty method :

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 };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文