EF Core 3.1 Breaks Left Join where Navigation Properties missing
This started out as a blog post. However, I thought I'd share it here as there seems to be a case where EF Core 3.1 breaks Left Joins as you upgrade from .NET Core 2.2 to .NET Core 3.1 when a navigation property is missing.
The error encountered (invalid SQL generation) is tricky to diagnose and doesn't give any clues; it's just a mysterious failure. I feel that there's probably a better way to surface the error related to a missing navigation property. So I thought I'd log this here to start a discussion.
Thanks for all the work you do on EF Core by the way - I'm really grateful ❤️
Now the blog:
Whilst running our app, we started encountering an error with an Entity Framework Query that looked like this:
var stuffWeCareAbout = await context.Things
.Include(thing => thing.ThisIsFine)
.Include(thing => thing.Problematic)
.Where(thing => thing.CreatedOn > startFromThisTime && thing.CreatedOn < endAtThisTime)
.OrderByDescending(thing => thing.CreatedOn)
.ToArrayAsync();
Join me!
As EF Core tried to join from the Things table to the Problematic table (some obfuscation in table names here), that which worked in .NET Core 2.2 was not working in .NET Core 3.1. Digging into the issue, we discovered EF Core was generating an invalid LEFT JOIN:
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
Failed executing DbCommand (18ms) [Parameters=[@__startFromThisTime_0='?' (DbType = DateTime2), @__endAtThisTime_1='?' (DbType = DateTime2)], CommandType='Text', CommandTimeout='30']
SELECT [o].[ThingId], [o].[AnonymousId], [o].[CreatedOn], [o].[Status], [o].[UpdatedOn], [o0].[Id], [o0].[ThingId], [o0].[Name], [o1].[ThingId], [o1].[Status], [o1].[CreatedOn], [o1].[ThingThingId], [o1].[SentOn]
FROM [Things] AS [o]
LEFT JOIN [ThisIsFines] AS [o0] ON [o].[ThingId] = [o0].[ThingId]
LEFT JOIN [Problematic] AS [o1] ON [o].[ThingId] = [o1].[ThingThingId]
WHERE ([o].[CreatedOn] @__startFromThisTime_0) AND ([o].[CreatedOn] < @__endAtThisTime_1)
ORDER BY [o].[CreatedOn] DESC, [o].[ThingId], [o1].[ThingId], [o1].[Status]
Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (18ms) [Parameters=[@__startFromThisTime_0='?' (DbType = DateTime2), @__endAtThisTime_1='?' (DbType = DateTime2)], CommandType='Text', CommandTimeout='30']
SELECT [o].[ThingId], [o].[AnonymousId], [o].[CreatedOn], [o].[Status], [o].[UpdatedOn], [o0].[Id], [o0].[ThingId], [o0].[Name], [o1].[ThingId], [o1].[Status], [o1].[CreatedOn], [o1].[ThingThingId], [o1].[SentOn]
FROM [Things] AS [o]
LEFT JOIN [ThisIsFines] AS [o0] ON [o].[ThingId] = [o0].[ThingId]
LEFT JOIN [Problematic] AS [o1] ON [o].[ThingId] = [o1].[ThingThingId]
WHERE ([o].[CreatedOn] @__startFromThisTime_0) AND ([o].[CreatedOn] < @__endAtThisTime_1)
ORDER BY [o].[CreatedOn] DESC, [o].[ThingId], [o1].[ThingId], [o1].[Status]
Do you see it? Probably not; it took us a while too... The issue lay here:
LEFT JOIN [Problematic] AS [o1] ON [o].[ThingId] = [o1].[ThingThingId]
This should actually have been:
LEFT JOIN [Problematic] AS [o1] ON [o].[ThingId] = [o1].[ThingId]
For some reason EF Core was looking for ThingThingId where it should have looked for ThingId. But why?
Navigation properties to the rescue!
This was the Problematic class:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Our.App
{
public class Problematic
{
[ForeignKey("Thing")]
[Required]
public Guid ThingId { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public DateTime SentOn { get; set; }
}
}
If you look closely you'll see it has a ForeignKey but no accompanying Navigation property. So let's add one:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Our.App
{
public class Problematic
{
[ForeignKey("Thing")]
[Required]
public Guid ThingId { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public DateTime SentOn { get; set; }
/* THIS NAVIGATION PROPERTY IS WHAT WE NEEDED!!! */
public virtual Thing Thing { get; set; }
}
}
With this in place our app starts generating the SQL we need.
Further technical details
EF Core version: 3.1 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET Core 3.1 Operating system: Windows 10 IDE: VS Code
EF Core model has changed for the configuration you are using. Query changes are just following model changes. Share your full model code. You may be hitting this https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#fkp
Also [ForeignKey("Thing")] configures nothing if there is no navigation named Thing in your entityType. You need to use Fluent API to configure the FK rather than data annotation which is being ignored. (This behavior was same in 2.2 also)
Thanks for responding @smitpatel !
Share your full model code.
Could you elaborate on what you mean by this? You'd like to see the Thing model that Problematic connects to?
Also
[ForeignKey("Thing")]configures nothing if there is no navigation named Thing in your entityType.
Is this why adding the navigation property fixed my issue? The introduction of the navigation property means that the ForeignKey is used?
Could you elaborate on what you mean by this? You'd like to see the Thing model that Problematic connects to?
All model classes and your DbContext. Or you can submit a self-contained runnable repro code.
Is this why adding the navigation property fixed my issue? The introduction of the navigation property means that the ForeignKey is used?
Yes, if you configure the FK using fluent API what FKAttribute would do with Navigation then things should work.
All model classes and your DbContext. Or you can submit a self-contained runnable repro code.
It's a private repo which I'm unable to share publicly. Could I zip up the classes and email them to you directly instead? If you don't want to expose your email address then please mail me at [email protected] and I can respond.
@johnnyreilly Sent you email.
Thanks @ajcvickers - I have it
Forwarded to @AndriySvyryd to take a look at the model.
You are experiencing this breaking change. Sent email with details.
I have Same Problem Here Is my class
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime DateOfBrith { get; set; }
public Gender Gender { get; set; }
//public int DepartmentId { get; set; }
public string PhotoPath { get; set; }
public virtual Department Department { get; set; }
}
public class Department { public int DepartmentId { get; set; } public string DepartmentName { get; set; } } public void ConfigureServices(IServiceCollection services) {
//services.AddDbContext<DataContext>(options =>
// options.UseSqlServer(Configuration["DataConnection"]));
services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration["DataConnection"]));
}
public class DataContext : DbContext
{
public DataContext(DbContextOptions
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.UsePropertyAccessMode(PropertyAccessMode.PreferFieldDuringConstruction);
// Code to seed data
}
}