You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Query: invalid SQL produced for queries with navigation inside predicate of SelectMany-Where-DefaultIfEmpty() pattern #11847
So I have this query with two LEFT JOINS.
Everything worked as expected when I had only one LEFT JOIN.
var dbQuery = from i in context.Ingredients
from ii in i.CombinationIngredients.Where(ci => ci.IngredientId == forIngredientId).DefaultIfEmpty()
select new
{
i.Id,
i.Name,
Linked = ii != null
};
However, when I add a second LEFT JOIN I see multiple queries in the database and I get an Exception.
var dbQuery = from i in context.Ingredients
from ii in i.CombinationIngredients.Where(ci => ci.IngredientId == forIngredientId).DefaultIfEmpty()
from t in i.Translations.Where(l => l.Language.Iso639_1 == language).DefaultIfEmpty()
select new
{
i.Id,
i.Name,
t.Translation,
Linked = ii != null
};
I add a Skip(...).Take(100) elsewhere in my code, but one of the queries is a "SELECT [all columns] FROM Ingredient" making this a HUGE performance hit!
But, what's even worse is that it doesn't work AT ALL.
Notice how I added t.Translation to the return value? I get the error "System.Data.SqlClient.SqlException: 'Invalid column name 'Translation'.'" EF somehow figures out that the column Translation is part of the Language table, while it's part of the IngredientTranslation table (which is what i.Translations points to).
One of the generated queries:
SELECT [i.Translations_groupItem.Language0].[Id], [i.Translations_groupItem.Language0].[Iso639_1], [i.Translations_groupItem.Language0].[Translation]
FROM [Language] AS [i.Translations_groupItem.Language0]
I do have a workaround, which is to just write the full join.
var dbQuery = from i in context.Ingredients
from ii in i.CombinationIngredients.Where(ci => ci.IngredientId == forIngredientId).DefaultIfEmpty()
join tran in context.IngredientTranslations.Where(l => l.Language.Iso639_1 == language) on i.Id equals tran.IngredientId into tranGroup
from t in tranGroup.DefaultIfEmpty()
select new
{
i.Id,
i.Name,
t.Translation,
Linked = ii != null
};
I'd prefer to use the much shorter "from x in ..." syntax though. I know this works in the non-core EF version.
Further technical details
EF Core version: 2.1.0-preview1-final
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017 15.6.7
I'm not doing any table splitting, just pretty basic SQL/LINQ. The following sample can be copy/pasted into a console application and should run out of the box after having installed Microsoft.EntityFrameworkCore.SqlServer and having done a Migration to create the database.
usingMicrosoft.EntityFrameworkCore;usingSystem.Collections.Generic;usingSystem.Linq;namespaceEFCoreSample{classProgram{staticvoidMain(string[]args){using(varcontext=newEFCoreSampleContext()){// We need some data or the query will be optimized and a JOIN will be eliminated.varapple=newIngredient{Active=true,Name="Apple"};varpear=newIngredient{Active=true,Name="Pear"};vardutch=newLanguage{Active=true,Iso639_1="nl",Name="Dutch"};varenglish=newLanguage{Active=true,Iso639_1="en",Name="English"};context.Add(apple);context.Add(pear);context.Add(newIngredientIngredient{Ingredient=apple,CombinationIngredient=pear});context.Add(dutch);context.Add(english);context.Add(newIngredientTranslation{Ingredient=apple,Language=dutch,Translation="Appel"});context.Add(newIngredientTranslation{Ingredient=pear,Language=dutch,Translation="Peer"});context.SaveChanges();intforIngredientId=1;stringquery="";// Filter results on name.stringlanguage="nl";intpage=1;intpageSize=100;// The second LEFT JOIN with "from x in ..." does not work due to a bug in EF Core...// Need to write the complete "join ..." syntax.vardbQuery=fromiincontext.Ingredientsfromiiini.CombinationIngredients.Where(ci =>ci.IngredientId==forIngredientId).DefaultIfEmpty()fromtini.Translations.Where(l =>l.Language.Iso639_1==language).DefaultIfEmpty()//join tran in context.IngredientTranslations.Where(l => l.Language.Iso639_1 == language) on i.Id equals tran.IngredientId into tranGroup//from t in tranGroup.DefaultIfEmpty()selectnew{i.Id,i.Name,t.Translation,Linked=ii!=null};if(!string.IsNullOrWhiteSpace(query)){dbQuery=dbQuery.Where(i =>i.Name.Contains(query)||i.Translation.Contains(query));}varingredients=dbQuery.Select(i =>new{i.Id,Name=i.Translation??i.Name,i.Linked}).OrderBy(i =>i.Name).Skip((page-1)*pageSize).Take(pageSize).ToList();}}}publicclassEFCoreSampleContext:DbContext{publicvirtualDbSet<Ingredient>Ingredients{get;set;}publicvirtualDbSet<IngredientTranslation>IngredientTranslations{get;set;}publicvirtualDbSet<IngredientIngredient>IngredientIngredients{get;set;}publicvirtualDbSet<Language>Languages{get;set;}protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder){optionsBuilder.UseSqlServer(@"Server=.\;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true");}protectedoverridevoidOnModelCreating(ModelBuilderbuilder){base.OnModelCreating(builder);builder.Entity<Ingredient>().ToTable(nameof(Ingredient));builder.Entity<Ingredient>().HasMany(e =>e.IngredientIngredients).WithOne(e =>e.Ingredient).OnDelete(DeleteBehavior.Restrict);builder.Entity<Ingredient>().HasMany(e =>e.CombinationIngredients).WithOne(e =>e.CombinationIngredient).OnDelete(DeleteBehavior.Restrict);builder.Entity<IngredientIngredient>().ToTable(nameof(IngredientIngredient));builder.Entity<IngredientIngredient>().HasOne(ii =>ii.Ingredient).WithMany(i =>i.IngredientIngredients).OnDelete(DeleteBehavior.Restrict);builder.Entity<IngredientIngredient>().HasOne(ii =>ii.CombinationIngredient).WithMany(i =>i.CombinationIngredients).OnDelete(DeleteBehavior.Restrict);builder.Entity<IngredientTranslation>().ToTable(nameof(IngredientTranslation));builder.Entity<Language>().ToTable(nameof(Language));}}publicclassIngredient{publicintId{get;set;}publicstringName{get;set;}publicboolActive{get;set;}publicvirtualICollection<IngredientTranslation>Translations{get;set;}publicvirtualICollection<IngredientIngredient>IngredientIngredients{get;set;}publicvirtualICollection<IngredientIngredient>CombinationIngredients{get;set;}}publicclassIngredientIngredient{publicintId{get;set;}publicintIngredientId{get;set;}publicIngredientIngredient{get;set;}publicintCombinationIngredientId{get;set;}publicIngredientCombinationIngredient{get;set;}}publicclassIngredientTranslation{publicintId{get;set;}publicstringTranslation{get;set;}publicintIngredientId{get;set;}publicIngredientIngredient{get;set;}publicintLanguageId{get;set;}publicLanguageLanguage{get;set;}}publicclassLanguage{publicintId{get;set;}publicstringName{get;set;}publicboolActive{get;set;}publicstringIso639_1{get;set;}}}
Problem is the navigation inside the second DefaultIfEmpty(), if the query is simplified to:
from i in ctx.Ingredients
from ii in i.CombinationIngredients.Where(ci => ci.IngredientId == forIngredientId).DefaultIfEmpty()
from t in i.Translations.Where(l => l.LanguageId == 1).DefaultIfEmpty()
select new
{
i.Id,
i.Name,
t.Translation,
Linked = ii != null
};
we have no problem translating it:
SELECT [i].[Id], [i].[Name], [t].[Translation], CASE
WHEN [t0].[Id] IS NOT NULL
THEN CAST(1ASBIT) ELSE CAST(0ASBIT)
END AS [Linked]
FROM [Ingredient] AS [i]
LEFT JOIN (
SELECT [i.Translations].*FROM [IngredientTranslation] AS [i.Translations]
WHERE [i.Translations].[LanguageId] =1
) AS [t] ON [i].[Id] = [t].[IngredientId]
LEFT JOIN (
SELECT [i.CombinationIngredients].*FROM [IngredientIngredient] AS [i.CombinationIngredients]
WHERE [i.CombinationIngredients].[IngredientId] = @__forIngredientId_0
) AS [t0] ON [i].[Id] = [t0].[CombinationIngredientId]
changed the title [-]Issue with multiple "from x in....DefaultIfEmpty()" (LEFT JOINs)[/-][+]Query: invalid SQL produced for queries with navigation inside predicate of SelectMany-Where-DefaultIfEmpty() pattern[/+]on Apr 30, 2018
Activity
smitpatel commentedon Apr 28, 2018
@SanderRossel Share code for your model classes & DbContext. Are you using table splitting?
SanderRossel commentedon Apr 29, 2018
I'm not doing any table splitting, just pretty basic SQL/LINQ. The following sample can be copy/pasted into a console application and should run out of the box after having installed Microsoft.EntityFrameworkCore.SqlServer and having done a Migration to create the database.
divega commentedon Apr 30, 2018
@SanderRossel was this working for you with a previous version?
maumar commentedon Apr 30, 2018
Problem is the navigation inside the second DefaultIfEmpty(), if the query is simplified to:
we have no problem translating it:
[-]Issue with multiple "from x in....DefaultIfEmpty()" (LEFT JOINs)[/-][+]Query: invalid SQL produced for queries with navigation inside predicate of SelectMany-Where-DefaultIfEmpty() pattern[/+]maumar commentedon Apr 30, 2018
Simplified repro:
maumar commentedon Apr 30, 2018
Verified that this is not a regression - same problem happens on 2.0
22 remaining items
maumar commentedon Sep 11, 2019
verified this issue has been fixed in 3.0
Adding regression tests for issues that have been fixed already
Adding regression tests for issues that have been fixed already