2017-01-09 47 views
0

嘗試用許多外連接重寫SQL查詢到Linq很困難。許多SQL連接到LINQ的外連接

這是查詢:

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'"; 

我嘗試了很多東西,這是其中之一,但它提供了許多錯誤:(LOC已經宣佈,類型推斷在羣組加入失敗,ONLINE2找不到)

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 

因此,如何寫多個左外連接到LINQ?

+3

您可以使用與編寫單個左連接相同的方式編寫多個左連接。你的代碼在'on1'之後缺少'from_on1 on1.DefaultIfEmpty()'。然後你只需繼續 - 'join _on2 ...'而不是'from _on2'。 –

回答

1

左外連接是通過.DefaultIfEmpty()方法實現的。

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; 
+0

al right thanks! – Laurijssen