相关疑难解决方法(0)

LINQ to SQL - 具有多个连接条件的左外连接

我有以下SQL,我试图将其转换为LINQ:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f ON p.id = f.periodid AND f.otherid = 17
WHERE p.companyid = 100
Run Code Online (Sandbox Code Playgroud)

我已经看到了左外连接的典型实现(即into x from y in x.DefaultIfEmpty()等),但我不确定如何引入其他连接条件(AND f.otherid = 17)

编辑

为什么AND f.otherid = 17条件是JOIN的一部分而不是WHERE子句?因为f某些行可能不存在,我仍然希望包含这些行.如果条件在WHERE子句中应用,在JOIN之后 - 那么我没有得到我想要的行为.

不幸的是:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100 && fgi.otherid == 17
select f.value
Run Code Online (Sandbox Code Playgroud)

似乎等同于:

SELECT …
Run Code Online (Sandbox Code Playgroud)

c# sql linq outer-join linq-to-sql

144
推荐指数
4
解决办法
14万
查看次数

LINQ 中的 C# 左连接

不确定如何将以下 sql 转换为 LINQ 表达式。我的数据库确实使用参照完整性,并且表内容与表 Content_Training 以 1 对多的关系(例如:1 个内容可以有多个 content_trainings)。

select c.ContentId, c.Name, ct.TrainingTypeId 
from dbo.Content c left join dbo.ContentTraining ct on c.ContentId = ct.ContentId
where c.ExpirationDate is not null
order by ct.TrainingTypeId, c.Name
Run Code Online (Sandbox Code Playgroud)

我试过这个,这似乎有效。但是,我不确定“let”关键字的用法。

var data = (from c in context.Contents
let ct = ( from t in context.Content_Training where t.ContentId == c.ContentId
select new { t.TrainingTypeId } ).FirstOrDefault()
where c.ExpirationDate.HasValue
orderby ct.TrainingTypeId, c.Name
select new { c.ContentId, c.Name, ct.TrainingTypeId } ).ToList();
Run Code Online (Sandbox Code Playgroud)

c# sql linq entity-framework

0
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

linq ×2

sql ×2

entity-framework ×1

linq-to-sql ×1

outer-join ×1