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
Missing navigated property data when using AsNoTracking, Include, Where #10561
public class SubConfig
{
public int Id { get; set; }
public int ConfigId { get; set; }
public string Value { get; set; }
}
public class Config
{
public int Id { get; set; }
public int? TenantId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public DateTimeOffset LastModified { get; set; }
public virtual ICollection<SubConfig> SubConfigs{ get; set; }
}
@JimBobSquarePants - The behavior is as expected.
In order1 you asked to load Order.OrderProducts property so that navigation is populated but OrderProduct.Product is not specified to be included. If you want Product navigation to be populated then query should be written like this. var order1 = db.Orders.AsNoTracking().Include(x => x.OrderProducts).ThenInclude(x => x.Product).First();
(p.s. First without predicate & order by is non-deterministic)
The second query (without AsNoTracking) is working because you are using same context, and the queried order will be fixed up with other entities which are being tracked (which is essentially whole graph you just saved). So you see non-null Product.
@JimBobSquarePants - The behavior is as expected.
In order1 you asked to load Order.OrderProducts property so that navigation is populated but OrderProduct.Product is not specified to be included. If you want Product navigation to be populated then query should be written like this. var order1 = db.Orders.AsNoTracking().Include(x => x.OrderProducts).ThenInclude(x => x.Product).First();
That's unfortunately verbose syntax which I very much hope will be improved upon in the future.
(p.s. First without predicate & order by is non-deterministic)
Again, disappointing. If the behaviour for First() is non-deterministic, then I would say your API is broken.
Again, disappointing. If the behaviour for First() is non-deterministic, then I would say your API is broken.
It is not behavior of First or EF Core. It is database storage behavior. Enumerable.First always gives first element of the sequence. But when you do db.Orders.First() then you are asking for first record of Order sequence/table. What is the ordering of records inside table is dependent on database. SqlServer records are ordered on PK property. Same is not true for postgre. Further database providers like document db which has data stored across multiple clusters would fetch first document from closest cluster for faster access. There is no default ordering standard on how database should store records so yes result will change if you change your database provider.
Shorter syntax would be db.Orders.AsNoTracking().Include("OrderProducts.Product").First();
The syntax would be improved in future when many-to-many without join table implemented. See #10508
Apologies for that. For string based include you need to write dotted name fully. We haven't added ThenInclude with string parameter due to lack of type information. The whole purpose of ThenInclude method is to provide intellisense support.
@smitpatel
Thank you for the code.
With this particular test data I also could not reproduce the issue, so I modified it. You can find the code below. I also want to denote that this happens from time to time, but not on every execution. If you run provided code multiple times, sometimes it finishes with no error, sometimes not.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace EFSampleApp
{
public class Program
{
public static void Main(string[] args)
{
using (var db = new MyContext())
{
// Recreate database
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
var tenant = new Tenant { Id = new Guid("CC0F45D4-3670-49B5-B67C-81300F2B9E5A") };
db.Tenants.Add(tenant);
db.AddRange(new Config
{
Name = "cas",
LastModified = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
Value = "config/cas"
}, new Config
{
Name = "cas",
TenantId = tenant.Id,
LastModified = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
Value = "config/cas",
SubConfigs = Enumerable.Range(0, 20).Select(x => new SubConfig() { Value = Guid.NewGuid().ToString() }).ToList()
},
new Config
{
Name = "casa",
TenantId = tenant.Id,
LastModified = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
SubConfigs = Enumerable.Range(0, 20).Select(x => new SubConfig() { Value = Guid.NewGuid().ToString() }).ToList(),
Value = "config/casa"
},
new Config
{
Name = "casa",
LastModified = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
Value = "config/casa"
});
db.SaveChanges();
}
using (var db = new MyContext())
{
// Run queries
var date = new DateTime(2017, 1, 1);
var delta = db.Configs.Include(x => x.SubConfigs).AsNoTracking().Where(x => ((x.LastModified > date) || x.TenantId != null)).ToList();
var deltaFull = db.Configs.Include(x => x.SubConfigs).AsNoTracking().Where(x => delta.Select(c => c.Name).Contains(x.Name)).ToList();
var deltaWithConfig = delta.Where(x => x.TenantId != null && x.SubConfigs.Any()).ToList();
var deltaFullWithConfig = deltaFull.Where(x => x.TenantId != null && x.SubConfigs.Any()).ToList();
if (deltaFullWithConfig.Count != deltaWithConfig.Count)
throw new ApplicationException();
Console.WriteLine(deltaFull.First().SubConfigs.Count);
}
Console.WriteLine("Program finished.");
}
}
public class MyContext : DbContext
{
private static ILoggerFactory LoggerFactory => new LoggerFactory().AddConsole(LogLevel.Trace);
// Declare DBSets
public DbSet<Config> Configs { get; set; }
public DbSet<Tenant> Tenants { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Select 1 provider
optionsBuilder
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=_ModelApp;Trusted_Connection=True;Connect Timeout=5;ConnectRetryCount=0")
//.UseSqlite("filename=_modelApp.db")
//.UseInMemoryDatabase(databaseName: "_modelApp")
.EnableSensitiveDataLogging()
.UseLoggerFactory(LoggerFactory);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Configure model
}
}
public class SubConfig
{
public Guid Id { get; set; }
public Guid ConfigId { get; set; }
public string Value { get; set; }
public virtual Config Config { get; set; }
}
public class Tenant
{
public Guid Id { get; set; }
public virtual ICollection<Config> Configurations { get; set; }
}
public class Config
{
public Guid Id { get; set; }
public Guid? TenantId { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public DateTime LastModified { get; set; }
public virtual ICollection<SubConfig> SubConfigs { get; set; }
}
}
In my local tests, I found that if I started from the other end (Authors in this example), and did my include from there (and then moved on to filtering based on BlogPosts) - all worked as expected.
Entirely true. I simplified my model a bit too much. I actually have an extra relation, my "authors" have a number of "properties" (another table).
So the code is actually like this (A Reservation has many Applicants, Applicants have many Reservations. Applicants have many Properties). I'm interested in all Applicants for a Reservation, and since semantically the Reservation is the "primary" object, I started from there like below - I'm then missing the Properties on my Applicants.
db.Reservations
.Where(s => s.Id == reservationID)
.SelectMany(s => s.Applicants)
// .Where(s => .. somthing ..) -- omitted, not relevant
.Select(s => s.Applicant)
.Include(s => s.Properties)
.ToList();
// Output: List of applicants without Properties
I've coded this into a small sample that shows this. EF10561.zip
In my application, I've reworked the above into this:
db.Applicants
.Include(s => s.Properties)
.Where(s => s.Reservations.Any(x => x.ReservationId == reservationID /* && other requirements */))
.ToList();
// Output: List of applicants with Properties
Activity
JimBobSquarePants commentedon Dec 21, 2017
I'm fairly certain that this issue is affecting many-to-many relationships also.
Given the following classes:
With the following
DbContextand setupThe following line will fail to map properly with only the property
ProductIdof eachOrderProductmapped, not theProductproperty itself.Without using
AsNoTracking()this works wellAll technical details are the same as above.
smitpatel commentedon Dec 21, 2017
@JimBobSquarePants - The behavior is as expected.
In
order1you asked to loadOrder.OrderProductsproperty so that navigation is populated butOrderProduct.Productis not specified to be included. If you wantProductnavigation to be populated then query should be written like this.var order1 = db.Orders.AsNoTracking().Include(x => x.OrderProducts).ThenInclude(x => x.Product).First();(p.s. First without predicate & order by is non-deterministic)
The second query (without
AsNoTracking) is working because you are using same context, and the queried order will be fixed up with other entities which are being tracked (which is essentially whole graph you just saved). So you see non-null Product.smitpatel commentedon Dec 21, 2017
@alex-zyl - I am not able to reproduce this. Can you modify following code to demonstrate the issue you are seeing?
JimBobSquarePants commentedon Dec 21, 2017
@smitpatel
That's unfortunately verbose syntax which I very much hope will be improved upon in the future.
Again, disappointing. If the behaviour for
First()is non-deterministic, then I would say your API is broken.There are issues in your querying API.
For example, this is impossible.
db.Orders.AsNoTracking().Include("OrderProducts").ThenInclude("Product").First();If you are going to offer alternative syntax for non-public properties you should make the functionality equivalent.
smitpatel commentedon Dec 21, 2017
It is not behavior of First or EF Core. It is database storage behavior.
Enumerable.Firstalways gives first element of the sequence. But when you dodb.Orders.First()then you are asking for first record ofOrdersequence/table. What is the ordering of records inside table is dependent on database. SqlServer records are ordered on PK property. Same is not true for postgre. Further database providers like document db which has data stored across multiple clusters would fetch first document from closest cluster for faster access. There is no default ordering standard on how database should store records so yes result will change if you change your database provider.Shorter syntax would be
db.Orders.AsNoTracking().Include("OrderProducts.Product").First();The syntax would be improved in future when many-to-many without join table implemented. See #10508
JimBobSquarePants commentedon Dec 22, 2017
That makes more sense.
First()is deterministic then based on context which I would expect.ThenIncludeextendsIIncludableQueryablenotIQueryableso the first syntax is not possible.smitpatel commentedon Dec 22, 2017
Apologies for that. For string based include you need to write dotted name fully. We haven't added
ThenIncludewith string parameter due to lack of type information. The whole purpose ofThenIncludemethod is to provide intellisense support.alex-zyl commentedon Dec 22, 2017
@smitpatel
Thank you for the code.
With this particular test data I also could not reproduce the issue, so I modified it. You can find the code below. I also want to denote that this happens from time to time, but not on every execution. If you run provided code multiple times, sometimes it finishes with no error, sometimes not.
LordMike commentedon Jan 12, 2018
I came here as I'm experiencing what seems like a bug in
.ThenInclude, probably much like the many-to-many example above. Am I to understand that ...In a hypothetical setup with types
BlogPost<->BlogPostAuthors<->Author, that if I "start" my query onBlogPostlike this:.. it will not work? (reason for doing above is a series of filtering on BlogPosts)
From what I gather, then, (untested), it should be like this.
In my local tests, I found that if I started from the other end (Authors in this example), and did my include from there (and then moved on to filtering based on BlogPosts) - all worked as expected.
maumar commentedon Jan 13, 2018
@LordMike
should work. If authors are not being pulled for you, could you share your model (entities and contents of DbContext.OnModelCreating)?
LordMike commentedon Jan 14, 2018
Entirely true. I simplified my model a bit too much. I actually have an extra relation, my "authors" have a number of "properties" (another table).
So the code is actually like this (A Reservation has many Applicants, Applicants have many Reservations. Applicants have many Properties). I'm interested in all Applicants for a Reservation, and since semantically the Reservation is the "primary" object, I started from there like below - I'm then missing the Properties on my Applicants.
I've coded this into a small sample that shows this.
EF10561.zip
In my application, I've reworked the above into this:
maumar commentedon Mar 6, 2018
@alex-zyl the repro you provided works correctly in the current bits, closing