渴望加载

预先加载可让你一次加载所有需要的实体。如果你希望在一次数据库调用中让所有实体都可以工作,那么就可以选择 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();