Since upgrading from .NET Framework to .NET Core, I've encountered an unexpected behavior in Entity Framework Core related to the use of .Include() and .AsNoTracking() methods.
Consider the following entities:
public class Entity1
{
public int Id { get; set; }
public string Name { get; set; }
public int Entity2Id { get; set; }
public Entity2 Entity2 { get; set; }
}
public class Entity2
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Entity1> Entity1s { get; set; }
}
When I execute the query
Context.Entity1s.AsNoTracking().Include(x => x.Entity2)
and then attempt to access Entity2.Entity1s on the result, only a single element (the parent) is displayed instead of the entire list.
However, removing .AsNoTracking() results in the expected behavior, displaying the complete list of Entity1 elements that are linked to Entity2.
I'm trying to understand why this discrepancy occurs and why it behaves differently in EF Core.
This is expected behavior, use
AsNoTrackingWithIdentityResolutioninstead of justAsNoTracking:Which should result in the desired output (if all the needed entities where fetched in the query).
From the Identity resolution section of the docs: