Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

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

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)

EDIT

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.

Unfortunately this:

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

seems to be equivalent to this:

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

which is not quite what I'm after.

2 Answers

0 votes
by (40.7k points)

Before calling DefaultIfEmpty(), you need to introduce your join condition. You should just use extension method syntax like this:

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 else you can use the below 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

Enroll yourself in the SQL server certification to learn in-depth about SQL statements, queries and become proficient in SQL. 

0 votes
by (1.5k points)

Yes you are absolutely correct at the placement of f.otherid=17. That need to be part of join clause to get the exact answer.

Here is the correct LINQ equivalent to SQL.Check following code

var query = from p in context.Periods

join f in context.Facts on new { p.id, OtherId = 17 } equals new { f.periodid, f.otherid }

where p.companyid == 100

select f.value;

Related questions

0 votes
1 answer
0 votes
2 answers
asked Jul 30, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 5, 2019 in SQL by Tech4ever (20.3k points)
0 votes
3 answers

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...