簡體   English   中英

Entity Framework Core Eager Loading 然后包含在集合中

[英]Entity Framework Core Eager Loading Then Include on a collection

我想在執行查詢時包含三個模型。

這是場景。

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

我可以像這樣急切地加載 SaleNotes...

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

但是,嘗試使用 ThenInclude 從 SaleNote 中預先加載 User 模型具有挑戰性,因為它是一個集合。 我找不到任何關於如何急切加載此場景的示例。 有人可以提供以下 ThenInclude 中的代碼以加載集合中每個項目的用戶。

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

SaleNotes是集合導航屬性並不重要。 它對於引用和集合的工作方式應該相同:

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

但據我所知,EF7 還支持使用 Select 擴展方法的舊多級 Include 語法:

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

作為參考,最新版本(發布時)EF Core 1.1.0 也支持此場景的顯式加載。 像這樣的東西...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM