LINQ to SQL - 複数の結合条件を持つ左外部結合 質問する

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

左外部結合の典型的な実装(などinto x from y in x.DefaultIfEmpty())を見たことがありますが、他の結合条件(AND f.otherid = 17)をどのように導入すればよいかわかりません。

編集

なぜAND f.otherid = 17条件は WHERE 句ではなく JOIN の一部なのでしょうか?f一部の行には条件が存在しない可能性があり、それでもこれらの行を含めたいからです。条件が JOIN の後の WHERE 句に適用された場合、必要な動作が得られません。

残念ながらこれ:

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

それは私が求めているものとは少し違います。

ベストアンサー1

呼び出す前に結合条件を導入する必要がありますDefaultIfEmpty()拡張メソッド構文を使用します:

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

または、サブクエリを使用することもできます。

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

おすすめ記事