Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

c# - Entity Framework Core Eager Loading Then Include on a collection

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(...);
question from:https://stackoverflow.com/questions/38044451/entity-framework-core-eager-loading-then-include-on-a-collection

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...