简体   繁体   中英

LINQ: How to perform a RIGHT OUTER JOIN?

I'm trying to make all B, S, M table combinations with all joins.

B in S in M

from var0 in ctx.B
join var1 in ctx.S on var0.B_id equals var1.parentId into var1Group
from var1 in var1Group
join var2 in ctx.M on var1.S_id equals var2.parentId 

B in S le M

from var0 in ctx.B
join var1 in ctx.S on var0.B_id equals var1.parentId into var1Group
from var1 in var1Group
join var2 in ctx.M on var1.S_id equals var2.parentId into var2Group
from var2 in var2Group.DefaultIfEmpty()

B le S le M

from var0 in ctx.B
join var1 in ctx.S on var0.B_id equals var1.parentId into var1Group         
from var1 in var1Group.DefaultIfEmpty()
join var2 in ctx.M on var1.S_id equals var2.parentId into var2Group
from var2 in var2Group.DefaultIfEmpty()

How to make (B le S ri M) or (B in S ri M)?

This supposed to be B in S ri M:

from var0 in ctx.B
join var1 in ctx.S on var0.B_id equals var1.parentId into var1Group
from var2 in ctx.M 
join var1 in var1Group on var1.S_id equals var2.parentId into var2Group
from var2 in var2Group.DefaultIfEmpty()

If I'm trying something like above, I get "The name 'var1Group' does not exist in the current context"

For a right join you simply need to swap the two sides and do a left join. This cannot be done in a "straight" LINQ query. You need two query expressions combined.

So first assign the result of B le S into a variable:

var q1 =
from var0 in ctx.B
join var1 in ctx.S on var0.B_id equals var1.parentId into var1Group into j
from var1 in j.DefaultIfEmpty()
select new { var0, var1 };

Then, left join with the sides reversed:

var q2 =
from var1 in ctx.M
join var2 in q1 /*!!!*/ on var1.S_id equals var2.parentId into j //approximate code
from var2 in j.DefaultIfEmpty()
//continue query

This code is quickly copied together. You'll need to fix some obvious problems. I hope the key idea is clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM