How do you perform a left outer join using linq extension methods

前端 未结 7 1148
灰色年华
灰色年华 2020-11-22 10:12

Assuming I have a left outer join as such:

from f in Foo
join b in Bar on f.Foo_Id equals b.Foo_Id into g
from result in g.DefaultIfEmpty()
select new { Foo          


        
7条回答
  •  有刺的猬
    2020-11-22 10:41

    Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:

    var qry = Foos.GroupJoin(
          Bars.OrderByDescending(b => b.Id),
          foo => foo.Foo_Id,
          bar => bar.Foo_Id,
          (f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });
    

    Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).

提交回复
热议问题