2017-08-28 139 views
0

我想加盟LINQ C#三個SQL表的SQL低於LINQ查詢不返回預期的結果

SELECT 
    rpp.* 
FROM dbo.Orgs ao 
LEFT JOIN dbo.Afflia rpa 
    ON rpa.AccountId = ao.ID 
INNER JOIN dbo.reports rpp 
    ON rpp.Id = rpa.reporttId 
WHERE ao.Name like '%xyz%' 

上面的查詢返回的數據,但相當於LINQ查詢不如下

from a in context.Orgs 
join aff in context.Afflia on a.ID equals aff.AccountId 
join prescriber in context.Reports on aff.reportId equals prescriber.Id 
where a.ORG_NAME.Contains("xyz") 

我可以知道哪裏的錯誤是什麼?

+0

你確定這是等價的Linq查詢嗎?我通常使用方法的語法,但只是看着它,我會說這會創建所有內部連接。如果他們真的是一樣的,你可以用一個探查器來檢查嗎? –

+0

因爲您正在嘗試執行內連接而不是左連接。你可以看看[這裏](https://stackoverflow.com/questions/3404975/left-outer-join-in-linq)如何正確地做到這一點。 – Vitali

+0

請在SQL和LINQ查詢中使用有意義的變量名稱! – axlj

回答

1

在SQL你正在做一個LEFT JOIN來dbo.Afflia,但在你的LINQ你正在做一個內部聯接。您需要添加「DefaultIfEmpty(),例如

from aff in context.Afflia.Where(join condition here).DefaultIfEmpty() 
1

你可以這樣做:

 var prescribers = (from a in context.Orgs 
          from aff in context.Afflia.Where(aff => aff.AccountId == a.ID) 
          from prescriber in context.Reports.Where(pres => pres.Id == aff.reportId) 
          where a.ORG_NAME.Contains("xyz") 
          select prescriber) 
          .ToList(); 
1

在LINQ你是INNER JOIN,但在SQL中,你是LEFT JOIN

試試這個。 :

from a in context.Orgs 
join aff in context.Afflia on a.ID equals aff.AccountId into affs 
from aff in affs.DefaultIfEmpty() 
join prescriber in context.Reports on aff.reportId equals prescriber.Id 
where a.ORG_NAME.Contains("xyz")