C# LINQ查询未返回预期结果

C# LINQ查询未返回预期结果,c#,linq,join,C#,Linq,Join,我试图在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.Or

我试图在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")

我可以知道错误在哪里吗?

在SQL中,您正在对dbo.Afflia进行左连接,但在LINQ中,您正在进行内部连接。您需要添加“DefaultIfEmpty(),例如


在SQL中,您正在对dbo.Afflia进行左连接,但在LINQ中,您正在进行内部连接

你可以做:

        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();
你可以做:

        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();

在LINQ中,您进行了内部联接,但在SQL中,您进行了左联接

请尝试以下方法:

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")

在LINQ中,您进行了内部联接,但在SQL中,您进行了左联接

请尝试以下方法:

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")

您确定这是等效的Linq查询吗?我通常使用方法语法,但只要看看它,我会说这会创建所有内部连接。你能用分析器检查一下它们是否真的是一样的吗?因为你试图做内部连接而不是左连接。您可以看看如何正确操作。请在SQL和LINQ查询中使用有意义的变量名!您确定这是等效的Linq查询吗?我通常使用方法语法,但只要看看它,我会说这会创建所有内部连接。你能用分析器检查一下它们是否真的是一样的吗?因为你试图做内部连接而不是左连接。您可以看看如何正确操作。请在SQL和LINQ查询中使用有意义的变量名!