开发者

How to do an outer join in LINQ?

开发者 https://www.devze.com 2023-03-16 13:51 出处:网络
I have defined two entities that map to two tables in my database. In SQL I would do a join like this:

I have defined two entities that map to two tables in my database. In SQL I would do a join like this:

select *
from tableA a
left outer join tableB b on b.ID = a.ID
where some co开发者_Go百科ndition

How might I do this with a LINQ query?


Using Labda Expressions you use a GroupJoin

Example:

var query =
  People
  .GroupJoin(
    Pets,
    person => person.PersonId,
    pet => per.Owner,
    (person, petCollection) =>
       new
       {
          Person = person,
          Pets = petCollection.Select(pet => pet.Name),
       });


See: How to: Perform Left Outer Joins (C# Programming Guide) on MSDN.

For example:

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) };
0

精彩评论

暂无评论...
验证码 换一张
取 消