如何创建左联接而不是内部联接?

时间:2019-06-17 16:01:33

标签: c# entity-framework linq linq-to-entities

我有一个SQL查询,正在转换为Linq,我想使用“左联接”而不是“内部联接”。

我尝试了DefaultIfEmpty()方法,但是没有运气。

Sql查询:

SELECT t0.*, t1.* FROM entity AS t0  
LEFT JOIN migration_logs AS t1 ON (CAST(t0.id AS CHAR) = t1.ObjectId and  'SASParty' = t1.ObjectType) 
where t1.status is null || t1.Status <> '1' ORDER BY t0.id LIMIT 0, 10;

Linq查询:

Entities
.Join(Migration_logs, 
e => new { id = e.Id.ToString(), ObjectType = "SASParty" }, 
mlog => new { id = mlog.ObjectId, mlog.ObjectType }, 
(e, mlog) => new {e,mlog})
.Where(result => result.mlog.Status == null || result.mlog.Status !=  "1").DefaultIfEmpty().ToList()

我正在使用linqpad,当我执行linq查询时,它将生成以下sql查询:

SELECT t0.*
FROM entity AS t0
INNER JOIN migration_logs AS t1
ON ((CAST(t0.id AS CHAR) = t1.ObjectId) AND (@p0 = t1.ObjectType))
WHERE ((t1.Status IS NULL) OR (t1.Status <> @p1))

原始查询和生成的sql查询中存在一些细微差别,但我希望问题陈述清楚。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

我能够使用linq to sql查询并使用into子句找到解决方案。

(from e in Entities
join mlog in Migration_logs
on new { id = e.Id.ToString(), ObjectType = "SASParty" }
equals new { id = mlog.ObjectId, mlog.ObjectType }
into results
 from r in results.DefaultIfEmpty()
 where r.Status == null || r.Status != "1"
 select new
 {
  e
 })

答案 1 :(得分:0)

您要对要执行左联接的数量执行.DefaultIfEmpty()方法。也许此代码段可以帮助您

from e in Entities
join ml in Migration_lpgs on new { id=e.Id.ToString(), ObjectType="SASParty" } equals new { id=ml.Id.ToString(), mlog.ObjectType } into j
from e in j.DefaultIfEmpty()
where ml.Status == null || ml.Status !=  "1"
select e