Linq - Left outer join with dot notation
How would I do a left outer join in linq using dot notation?
Here's the query expression:
var query = from u in db.Users
join d in db.Defects on u.userID equals d.userID into defectsGroup
from d in defectsGroup.DefaultIfEmpty()
select new { u, d };
Here's what I tried:
var que开发者_开发知识库ry2 = db.Users.GroupJoin(db.Defects.DefaultIfEmpty(),
u => u.userID,
d => d.userID,
(user, defect) => new { user, defect });
But defect is showing as IEnumerable<Defect>
rather than just Defect
. I also tried:
var query2 = db.Users.GroupJoin(db.Defects,
u => u.userID,
d => d.userID,
(user, defect) => new { user, defect.DefaultIfEmpty() });
Which simply doesn't compile. All the online examples seem to use the (clearer) query syntax.
I think you want this:
var query2 = db.Users.GroupJoin(db.Defects,
u => u.userId,
d => d.userID,
(u, defectsGroup) => new { u, defectsGroup})
.SelectMany(z => z.defectsGroup.DefaultIfEmpty(),
(z, d) => new { z.u, d });
See my Edulinq blog post on query expressions for more details.
精彩评论