Eager loading via Include depends on QueryTrackingBehavior if navigation property is pre-initialized.
(title and description edited one hour after opened)
The following code performs the same query (and the same checks) for all values of QueryTrackingBehavior, and shows different results for different values. Only the behavior for QueryTrackingBehavior.TrackAll complies with the breaking change regarding non-null reference navigations.
Program.cs
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace EfCoreEagerIncludeWithTrackingProblem
{
public class Program
{
public class Blog
{
public Blog()
{
Owner = new Person(); // Without this line nothing fails.
}
public Int32 Id { get; set; }
public Person Owner { get; set; }
}
public class Person
{
public Int32 Id { get; set; }
public String Name { get; set; }
}
public class BloggingContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EfCoreEagerIncludeWithTrackingProblemDb;ConnectRetryCount=0");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>();
}
}
private static void Main(string[] args)
{
using ( var context = new BloggingContext() )
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var blog = new Blog();
blog.Owner.Name = "Joe";
context.Add(blog);
context.SaveChanges();
Debug.Assert(blog.Id == 1);
Debug.Assert(blog.Owner.Id == 1);
Debug.Assert(blog.Owner.Name == "Joe");
}
using ( var context = new BloggingContext() )
{
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
var blog = context.Set<Blog>().Include(b => b.Owner).FirstOrDefault(b => b.Id == 1);
Debug.Assert(blog.Owner.Id == 1);
Debug.Assert(blog.Owner.Name == "Joe");
}
using ( var context = new BloggingContext() )
{
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTrackingWithIdentityResolution;
var blog = context.Set<Blog>().Include(b => b.Owner).FirstOrDefault(b => b.Id == 1);
Debug.Assert(blog.Owner.Id == 1);
Debug.Assert(blog.Owner.Name == "Joe");
}
using ( var context = new BloggingContext() )
{
context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.TrackAll;
var blog = context.Set<Blog>().Include(b => b.Owner).FirstOrDefault(b => b.Id == 1);
Debug.Assert(blog.Owner.Id == 1); // This fails because Id is 0.
Debug.Assert(blog.Owner.Name == "Joe"); // This fails because Name is null.
}
}
}
}
provider and version information
EF Core version: 5.0.0 and 5.0.1 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET Core 3.1 and .NET 5.0 Operating system: Windows 10 IDE: Visual Studio 2019 v16.8.3
Could this issue be related to issue #10042?
@GeroIwan I don't think this is related to that issue. This is the correct behavior for tracking queries--see https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/breaking-changes#nonnullreferences. However, see also https://github.com/dotnet/EntityFramework.Docs/issues/2693#issuecomment-697945887
@ajcvickers Does this mean that (at least at the moment) we cannot use non-nullable reference types for navigation properties?
@GeroIwan No, it means you can't eagerly initialize them to an empty entity instance.
@ajcvickers Okay, of course. But we have to suppress the compiler warnings then, or use the null-forgiving operator by assigning null!. Or is there another way beside these two possibilities?
CS8618 Non-nullable property 'Owner' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
@ajcvickers On https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/breaking-changes#nonnullreferences
it is written: "Starting with EF Core 5.0, non-null reference navigations are never overwritten by instances returned from a query."
There's no distinction between different QueryTrackingBehavior. Or am I missing something?
title and description edited
Notes from triage: It would be a breaking change to change the behavior of no-tracking queries, even though they don't have the behavior that we agreed on when we discussed the design. On the other hand, it is less of a breaking change to change the behavior for tracking queries to always overwrite existing entity values with values returned from the query. (Non-query fixup would remain unchanged.) Given that initializing empty entity instances eagerly is an anti-pattern that won't work correctly anyway regardless of what we do, we will investigate always overwriting for 6.0.
@GeroIwan Yes, you'll need to use one of the patterns for dealing with NRTs in this case. This behavior is supposed to be the same for all types of queries; it is a bug that no-tracking queries have different behavior.
I just realized that for QueryTrackingBehavior.TrackAll the loading/overwriting also depends on whether the pre-initialized property is on the dependent or principal side.
- When the foreign key
BlogIdis added toPersonthen the pre-initializedOwnernavigation ofBlogis overwritten. - In the original code,
Bloggets the foreign keyOwnerIdimplicitly, and the pre-initializedOwneris not overwritten.
@Gerolwan re the NRT question, see our docs on this question. To avoid using the null-forgiving operator, you can have a non-nullable property over a nullable backing field, and have the property's getter throw if the backing field is ever null. This properly exposes a non-nullable property (representing the fact that the navigation is required, and therefore never null when loaded), while at the same time raising an exception if the navigation property is accessed without having loaded it.
Force-initializing to null with the null-forgiving operator is also a valid possibility, though throwing an early, informative exception is better than returning null.
@roji Thanks for the valuable reply!