[英]Linq-to-Sql LEFT OUTER JOIN between 2 separate INNER JOINRS
Trying to generate the following SQL from Linq-To-Sql尝试从 Linq-To-Sql 生成以下 SQL
SELECT
parenttableA.Name AS parentA,
childtableA.Name AS childA,
parenttableB.Name AS parentB,
childtableB.Name AS childB
FROM parenttableA
INNER JOIN childtableA ON childtableA.parentid = parenttableA.id
LEFT OUTER JOIN
(
parenttableB
INNER JOIN childtableB ON childtableB.parentid = parenttableB.id
)
ON parenttableB.townid = parenttableA.townid
WHERE parenttableA.townid = 123
This SQL should return something like:此 SQL 应返回如下内容:
parentA childA parentB childB
======= ====== ======= ======
John Dave Paul Mark
Jim John (null) (null)
So, in other words:所以,换句话说:
How can I have 2 separate inner joins linked together with a LEFT OUTER JOIN so that I still get "A" records from town 123, even if no "B" records exist for that town?如何将 2 个单独的内部连接与 LEFT OUTER JOIN 链接在一起,以便我仍然从 123 镇获得“A”记录,即使该镇不存在“B”记录?
This should work for IQueryable
for enumerable you should add null checks这应该适用于IQueryable
for enumerable 你应该添加空检查
var query = from ptA in parenttableA
join ctA in childtableA on ptA.Id equals ctA.Id
join ptBctB in (from ptB in parenttableB
join ctB in childtableB on ptB.Id equals ctB.Id
select new { ptB, ctB }) on ptA.TownId equals ptBctB.ptB.TownId into ptBGroup
from ptBctBLeft in ptBGroup.DefaultIfEmpty()
where ptA.TownId == 123
select new
{
parentA = ptA.Name,
childA = ctA.Name,
parentB = ptBctBLeft.ptB.Name,
childB = ptBctBLeft.ctB.Name,
};
Also I think you can do this with just mapping configuration and have this as a property in your POCO but you need to post the EF config for that.此外,我认为您只需映射配置即可完成此操作,并将其作为 POCO 中的一个属性,但您需要为此发布 EF 配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.