我正在尝试在LINQ c#中为以下SQL
加入三个SQL表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 :(得分:1)
在您的SQL中,您正在对dbo.Afflia进行LEFT连接,但在您的LINQ中,您正在进行内部联接。您需要添加“DefaultIfEmpty(),例如
from aff in context.Afflia.Where(join condition here).DefaultIfEmpty()
答案 1 :(得分: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();
答案 2 :(得分:1)
在LINQ中,您进行了INNER连接,但在SQL中,您进行了LEFT连接。
请改为尝试:
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")