Entity Framework Core Eager Loading Then Include on a collection

左心房为你撑大大i 提交于 2019-12-03 14:45:18

问题


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:


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



回答2:


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


来源:https://stackoverflow.com/questions/38044451/entity-framework-core-eager-loading-then-include-on-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!