Load 方法

在某些情況下,您可能會想要將實體從資料庫載入內容,而不需立即對這些實體執行任何動作。 其中一個很好的範例是載入資料系結的實體,如本機資料 中所述 。 若要這樣做,其中一個常見方式是撰寫 LINQ 查詢,然後在其上呼叫 ToList,只為了立即捨棄已建立的清單。 Load 擴充方法的運作方式就像 ToList 一樣,不同之處在于它會避免完全建立清單。

本主題所示範的技巧同樣適用於使用 Code First 和 EF 設計工具所建立的模型。

以下是使用 Load 的兩個範例。 第一個取自 Windows Forms 資料系結應用程式,其中 Load 是用來在系結至本機集合之前查詢實體,如本機資料 中所述

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    _context = new ProductContext();

    _context.Categories.Load();
    categoryBindingSource.DataSource = _context.Categories.Local.ToBindingList();
}

第二個範例示範如何使用 Load 載入已篩選的相關實體集合,如載入相關實體 中所述

using (var context = new BloggingContext())
{
    var blog = context.Blogs.Find(1);

    // Load the posts with the 'entity-framework' tag related to a given blog
    context.Entry(blog)
        .Collection(b => b.Posts)
        .Query()
        .Where(p => p.Tags.Contains("entity-framework"))
        .Load();
}