C# 使用实体框架和 Lambda 表达式的左外连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16706927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Left Outer Join using Entity Framework and Lambda Expressions
提问by J. Davidson
Employee
id, name, datejoin, deptID
and another table that is
另一个表是
Marketing
id, name, deptID
What I am trying to do is search of deptID from Employee table in Marketing to see if it exists, if it doesn't exists want to add name and deptID from Employee table into Marketing table. Basically I believe it is left outer join.
我想要做的是从 Marketing 中的 Employee 表中搜索 deptID 以查看它是否存在,如果它不存在想要将 Employee 表中的 name 和 deptID 添加到 Marketing 表中。基本上我相信它是左外连接。
I am trying to do is using lambda expressions and EF I am new to this area so was wondering how to accomplish that. I have created the entities fine need to figure out the lambda expression
我想做的是使用 lambda 表达式和 EF 我是这个领域的新手,所以想知道如何实现这一点。我已经创建了需要找出 lambda 表达式的实体
tTlEntities sde = new tTlEntities();
sde.t_Marketing.Where(x=>x.deptID == t_Employee.deptID).
That is how far I went I know some outer joining is needed. Help Pleasee
这就是我走了多远我知道需要一些外部连接。请帮忙
回答by cheedep
You need DefaultIfEmpty(). Also the type will have to be anonymous and not employee as it needs more properties than employee.
你需要DefaultIfEmpty(). 此外,该类型必须是匿名的,而不是员工,因为它需要比员工更多的属性。
var leftList = (from emp in Employees
join d in Departments
on emp.deptID equals d.Id into output
from j in output.DefaultIfEmpty()
select new {id = emp.Id, name = emp.name, datejoin = emp.datejoin, deptname = d.name });
回答by cheedep
It could be done with a left outer join of employee to marketing and a check for null marketing results for the employee, or you can use not exists which in LINQ to Entities is:
可以通过将员工的左外部连接到市场营销并检查员工的空营销结果来完成,或者您可以使用 notexists 在 LINQ to Entities 中是:
tTlEntities sde = new tTlEntities();
var employeeQuery = sde.t_Employee.Where(
e=> !sde.t_Marketing.Any(m => m.deptID == e.deptID));
回答by VahidN
If your navigation propertyhas a nullable foreign key id, EF will create a left outer joinautomatically. If it's not nullable, the result would be an inner join. it's not necessary to write a join explicitly. just use the Includeextension method on the navigation property which has a nullable foreign key id.
如果您navigation property有一个nullable foreign key id,EF 将left outer join自动创建一个。如果它不可为空,则结果将是inner join. 没有必要显式地编写连接。只需Include在具有nullable foreign key id.

