npgsql / efcore.pg

Entity Framework Core provider for PostgreSQL

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: SQL LEFT JOIN clause varies based on declarative- vs. method-style join

smarts opened this issue · comments

  1. Declarative-style equijoin
from foo in dbContext.Set<Foo>()
join bar in dbContext.Set<Bar>() on
new { foo.Id, State = "Blah" } equals new { Id = bar.FooId, bar.State } into barGroupJoin
from subBar in barGroupJoin.DefaultIfEmpty()
select new { /* use subBar instead of bar */ }
  1. Method-style equijoin
from foo in dbContext.Set<Foo>()
from bar in dbContext.Set<Bar>().Where(x => x.FooId == foo.Id && x.State == "Blah").DefaultIfEmpty()
select new { /* use bar */ }

I generally prefer 2 because it's arguably just as easy to read, doesn't leave a variable that goes unused, etc.
But one thing I notice is that the former style will generate something like

LEFT JOIN mySchema."Bars" AS B ON B."FooId" = F."Id" AND B."State" = 'Blah'

while the latter generates something like

LEFT JOIN (
SELECTFROM mySchema."Bars" AS B
WHERE B."State" = 'Blah'
) as C ON C."FooId" = F."Id"

Is this intentional, and if so why?

This is a general SQL translation question that isn't related to the PostgreSQL provider, can you please move it to https://github.com/dotnet/efcore?