Entity Framework Core Eager Loading Then Include on a collection

c# entity-framework entity-framework-core

Question

I have three Models that I want to include when performing a query.

Here is the scenario.

public class Sale
{
     public int Id { get; set; }
     public List<SaleNote> SaleNotes { get; set; }
}

public class SaleNote
{
    public int Id { get; set; }
    public User User { get; set; }
}

public class User 
{
    public int Id { get; set; }
}

I can eager load the SaleNotes like this...

_dbContext.Sale.Include(s => s.SaleNotes);

However, trying to eager load the User model from the SaleNote using ThenInclude is challenging because it is a collection. I cannot find any examples on how to eager load this scenario. Can someone supply the code the goes in the following ThenInclude to load the User for each item in the collection.

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(...);
1
32
6/27/2016 12:37:30 AM

Accepted Answer

It doesn't matter that SaleNotes is collection navigation property. It should work the same for references and collections:

_dbContext.Sale.Include(s => s.SaleNotes).ThenInclude(sn=>sn.User);

But as far I know, EF7 also supports the old multi-level Include syntax using Select extension method:

_dbContext.Sale.Include(s => s.SaleNotes.Select(sn=>sn.User));
45
2/12/2020 9:10:10 PM

Popular Answer

For reference, the latest release of EF Core (1.1.0) also supports explicit loading for this scenario. Something like this...

using (var _dbContext = new DbContext())
{
    var sale = _dbcontext.Sale
        .Single(s => s.Id == 1);

    _dbcontext.Entry(sale)
        .Collection(n => n.SalesNotes)
        .Load();

    _dbcontext.Entry(sale)
        .Reference(u => u.User)
        .Load();
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow