【发布时间】:2011-06-29 23:02:29
【问题描述】:
我已经定义了两个实体,它们映射到我的数据库中的两个表。在 SQL 中,我会像这样进行连接:
select *
from tableA a
left outer join tableB b on b.ID = a.ID
where some condition
如何使用 LINQ 查询来做到这一点?
【问题讨论】:
标签: c# sql linq entity-framework linq-to-entities
我已经定义了两个实体,它们映射到我的数据库中的两个表。在 SQL 中,我会像这样进行连接:
select *
from tableA a
left outer join tableB b on b.ID = a.ID
where some condition
如何使用 LINQ 查询来做到这一点?
【问题讨论】:
标签: c# sql linq entity-framework linq-to-entities
使用 Labda 表达式,您使用 GroupJoin
例子:
var query =
People
.GroupJoin(
Pets,
person => person.PersonId,
pet => per.Owner,
(person, petCollection) =>
new
{
Person = person,
Pets = petCollection.Select(pet => pet.Name),
});
【讨论】:
请参阅:MSDN 上的How to: Perform Left Outer Joins (C# Programming Guide)。
例如:
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
【讨论】: