LINQ to SQL - 具有多个连接条件的左外连接 [英] LINQ to SQL - Left Outer Join with multiple join conditions

查看:43
本文介绍了LINQ to SQL - 具有多个连接条件的左外连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 SQL,我正在尝试将其转换为 LINQ:

I have the following SQL, which I am trying to translate to 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

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

I have seen the typical implementation of the left outer join (ie. into x from y in x.DefaultIfEmpty() etc.) but am unsure how to introduce the other join condition (AND f.otherid = 17)

编辑

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

Why is the AND f.otherid = 17 condition part of the JOIN instead of in the WHERE clause? Because f may not exist for some rows and I still want these rows to be included. If the condition is applied in the WHERE clause, after the JOIN - then I don't get the behaviour I want.

不幸的是:

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

似乎相当于:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f ON p.id = f.periodid 
WHERE p.companyid = 100 AND f.otherid = 17

这不是我想要的.

推荐答案

调用DefaultIfEmpty().我只会使用扩展方法语法:

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

或者你可以使用子查询:

Or you could use a subquery:

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

这篇关于LINQ to SQL - 具有多个连接条件的左外连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆