我已经定义了两个映射到数据库中两个表的实体。在SQL中我会像这样进行连接:
select *
from tableA a
left outer join tableB b on b.ID = a.ID
where some condition
如何使用LINQ查询执行此操作?
答案 0 :(得分:5)
使用Lambda表达式,您可以使用GroupJoin
示例:
var query =
People
.GroupJoin(
Pets,
person => person.PersonId,
pet => per.Owner,
(person, petCollection) =>
new
{
Person = person,
Pets = petCollection.Select(pet => pet.Name),
});
答案 1 :(得分:4)
请参阅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) };