Skip to content

Missing navigated property data when using AsNoTracking, Include, Where #10561

Closed as not planned

Description

@alex-zyl

We have the following entities

        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; }
        }

Database contains the following rows:

Id: 1
Name: TenantConfig
TenantId: 1
ConfigSubItems: { {Id:1}, {Id:2}, {Id:3} 

Id: 2
Name: SharedConfig
TenantId: null
ConfigSubItems: {}

When executing the following queries

var delta = db.Configs.Include(x => x.SubConfigs).AsNoTracking().Where(x=> ((x.LastModified > XXX) || x.TenantId != null)).ToList();
var deltaFull = db.Configs.Include(x => x.SubConfigs).AsNoTracking().Where(x => delta.Select(c => c.Name).Contains(x.Name)).ToList();

using EF Core 1.1.2:

deltaFull contains Config item for TenantId = 1 and collection of SubConfigs[3]

using EF Core 2.0.1

deltaFull contains Config item for TenantId = 1 and collection of SubConfigs[0]

Further technical details

EF Core version: 2.0.1
Database Provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
IDE: VS2017 15.5

Activity

  1. added this to the 2.1.0 milestone on Dec 18, 2017
  2. JimBobSquarePants commented on Dec 21, 2017

    @JimBobSquarePants

    I'm fairly certain that this issue is affecting many-to-many relationships also.

    Given the following classes:

    public class Order
    {
        public int Id { get; set; }
        public ICollection<OrderProduct> OrderProducts { get; set; } = new HashSet<OrderProduct>();
    }
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<OrderProduct> OrderProducts { get; set; } = new HashSet<OrderProduct>();
    }
    public class OrderProduct
    {
        public int OrderId { get; set; }
        public Order Order { get; set; }
        public int ProductId { get; set; }
        public Product Product { get; set; }
    }

    With the following DbContext and setup

    public class TestDbContext : DbContext
    {
        public DbSet<Order> Orders { get; set; }
        public DbSet<Product> Products { get; set; }
    
        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<OrderProduct>().HasKey(k => new { k.OrderId, k.ProductId });
            builder.Entity<OrderProduct>()
                .HasOne(p => p.Order)
                .WithMany(p => p.OrderProducts)
                .HasForeignKey(p => p.OrderId);
    
            builder.Entity<OrderProduct>()
                .HasOne(p => p.Product)
                .WithMany(p => p.OrderProducts)
                .HasForeignKey(p => p.ProductId);
        }
    
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseInMemoryDatabase("testdb");
        }
    }
    var db = new TestDbContext())
    db.Database.EnsureDeleted();
    db.Database.EnsureCreated();
    
    var products = new List<Product>
    {
        new Product() { Name = "Product1" },
        new Product() { Name = "Product2" }
    };
    
    var order = new Order();
    
    foreach (Product p in products)
    {
        order.OrderProducts.Add(new OrderProduct() { Order = order, Product = p }); 
    }
    
    db.AddRange(products);
    db.Add(order);
    db.SaveChanges();

    The following line will fail to map properly with only the property ProductId of each OrderProduct mapped, not the Product property itself.

    var order1 = db.Orders.AsNoTracking().Include(x => x.OrderProducts).First();

    Without using AsNoTracking() this works well

    var order2 = db.Orders.First();

    All technical details are the same as above.

  3. smitpatel commented on Dec 21, 2017

    @smitpatel
    Contributor

    @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.

  4. smitpatel commented on Dec 21, 2017

    @smitpatel
    Contributor

    @alex-zyl - I am not able to reproduce this. Can you modify following code to demonstrate the issue you are seeing?

    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();
    
                    // Seed database
                    db.AddRange(
                        new Config
                        {
                            Name = "TenantConfig",
                            TenantId = 1,
                            LastModified = DateTime.Now,
                            SubConfigs = new List<SubConfig>
                            {
                                new SubConfig(),
                                new SubConfig(),
                                new SubConfig()
                            }
                        },
                        new Config
                        {
                            Name = "SharedConfig"
                        });
    
                    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();
    
                    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; }
    
            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 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; }
        }
    }
  5. JimBobSquarePants commented on Dec 21, 2017

    @JimBobSquarePants

    @smitpatel

    @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.

    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.

  6. smitpatel commented on Dec 21, 2017

    @smitpatel
    Contributor

    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

  7. JimBobSquarePants commented on Dec 22, 2017

    @JimBobSquarePants

    if you change your database provider.

    That makes more sense. First() is deterministic then based on context which I would expect.

    ThenInclude extends IIncludableQueryable not IQueryable so the first syntax is not possible.

  8. smitpatel commented on Dec 22, 2017

    @smitpatel
    Contributor

    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.

  9. alex-zyl commented on Dec 22, 2017

    @alex-zyl
    Author

    @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; }
        }
    }
    
  10. LordMike commented on Jan 12, 2018

    @LordMike

    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 on BlogPost like this:

    _db.BlogPosts.SelectMany(s => s.Authors).Include(s => s.Author);
    

    .. 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.

    _db.BlogPosts.Include(s => s.Authors).ThenInclude(s => s.Author).SelectMany(s => s.Authors);
    

    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.

  11. maumar commented on Jan 13, 2018

    @maumar
    Contributor

    @LordMike

    db.BlogPosts.SelectMany(s => s.Authors).Include(s => s.Author);
    

    should work. If authors are not being pulled for you, could you share your model (entities and contents of DbContext.OnModelCreating)?

  12. LordMike commented on Jan 14, 2018

    @LordMike

    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
    
  13. modified the milestones: , 2.1.0 on Jan 17, 2018
  14. maumar commented on Mar 6, 2018

    @maumar
    Contributor

    @alex-zyl the repro you provided works correctly in the current bits, closing

  15. removed this from the milestone on Apr 7, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions