简体   繁体   中英

Many outer join with SQL to LINQ

Having a hard time with trying to rewrite an SQL query to Linq with many outer joins.

This is the query:

select on1.diskpath as d1,
on2.diskpath as d2,
of1.diskpath as d3,
of2.diskpath as d4,
on1.disknaam as n1,
on2.disknaam as n2,
of1.disknaam as n3,
of2.disknaam as n4
from tblstoragelocation
left join tblstoragedisks on1 on online1=on1.id
left join tblstoragedisks on2 on online2=on2.id
left join tblstoragedisks of1 on offline1=of1.id
left join tblstoragedisks of2 on offline2=of2.id where md5='xxx'";

I tried many things, this is one of them but it gives many errors: (loc is already declared, type inference failed in groupjoin, online2 could not be found)

from loc in fdc.tblStoragelocations
join _on1 in fdc.tblStoragedisks on loc.online1 equals _on1.id into on1
from _on2 in fdc.tblStoragedisks on loc.online2 equals _on2.id into on2

So how to write multiple left outer joins to LINQ?

Left outer join is achieved by .DefaultIfEmpty() method.

var q = 
    from iter_1 in collection_1
    join iter_2 in collection_2 on iter_1 equals iter_2 into join_1 
    from iter_2 in join_1.DefaultIfEmpty()
    join iter_3 in collection_3 on iter_2 equals iter_3 into join_2
    from iter_3 in join_2.DefaultIfEmpty()
    ...
    join iter_n in collection_n on iter_n_1 equals iter_n into join_n_1
    from iter_n in join_n_1.DefaultIfEmpty()
    select join_n_1;

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