渴望載入

預先載入可讓你一次載入所有需要的實體。如果你希望在一次資料庫呼叫中讓所有實體都可以工作,那麼就可以選擇 Eager 載入了。它還允許你載入多個級別。

你有兩個載入相關實體的選項,你可以選擇 Include 方法的強型別字串過載。 **

強打字

// Load one company with founder and address details
int companyId = ...;
Company company = context.Companies
    .Include(m => m.Founder)
    .Include(m => m.Addresses)
    .SingleOrDefault(m => m.Id == companyId);

// Load 5 companies with address details, also retrieve country and city
// information of addresses
List<Company> companies = context.Companies
    .Include(m => m.Addresses.Select(a => a.Country));
    .Include(m => m.Addresses.Select(a => a.City))
    .Take(5).ToList();

從 Entity Framework 4.1 開始,此方法可用。確保你有參考 using System.Data.Entity; 設定。

字串過載

// Load one company with founder and address details
int companyId = ...;
Company company = context.Companies
    .Include("Founder")
    .Include("Addresses")
    .SingleOrDefault(m => m.Id == companyId);

// Load 5 companies with address details, also retrieve country and city
// information of addresses
List<Company> companies = context.Companies
    .Include("Addresses.Country");
    .Include("Addresses.City"))
    .Take(5).ToList();