如何:使用延迟加载来加载相关对象(实体框架)
本主题介绍如何使用延迟加载来加载相关对象。 启用延迟加载后,在通过导航属性访问相关对象时,会加载这些相关对象。 您仍可以使用 Include 方法预先加载对象,或使用 LoadProperty 方法显式加载对象。 有关更多信息,请参见加载相关对象(实体框架)。
在实体框架 运行时中,ObjectContext 实例中的 LazyLoadingEnabled 属性的默认值为 false。 但是,如果您使用实体框架 工具创建新模型和对应的生成类,则在生成对象上下文的构造函数中,生成的代码将 LazyLoadingEnabled 设置为 true。
本主题中的示例基于 Adventure Works 销售模型。若要运行本主题中的代码,则必须已经将 Adventure Works 销售模型添加到了您的项目中,并且已经将项目配置为使用实体框架。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)或如何:手动配置实体框架项目和如何:手动定义实体数据模型(实体框架)。
示例
下面的示例显示十个联系人,并让用户选择一个。 根据所选联系人,随后将加载相关订单。
Class LazyLoading
Public Sub EnableLazyLoading()
Using context As New AdventureWorksEntities()
' You do not have to set context.ContextOptions.LazyLoadingEnabled to true
' if you used the Entity Framework to generate the object layer.
' The generated object context type sets lazy loading to true
' in the constructor.
context.ContextOptions.LazyLoadingEnabled = True
' Display ten contacts and select a contact
Dim contacts = context.Contacts.Take(10)
For Each c In contacts
Console.WriteLine(c.ContactID)
Next
Console.WriteLine("Select a customer:")
Dim contactID As Int32 = Convert.ToInt32(Console.ReadLine())
' Get a specified customer by contact ID.
Dim contact = context.Contacts.Where(Function(c) c.ContactID = contactID).FirstOrDefault()
' If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact.
For Each order As SalesOrderHeader In contact.SalesOrderHeaders
Console.WriteLine("SalesOrderID: {0} Order Date: {1} ", order.SalesOrderID, order.OrderDate)
Next
End Using
End Sub
End Class
class LazyLoading
{
public void EnableLazyLoading()
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
// You do not have to set context.ContextOptions.LazyLoadingEnabled to true
// if you used the Entity Framework to generate the object layer.
// The generated object context type sets lazy loading to true
// in the constructor.
context.ContextOptions.LazyLoadingEnabled = true;
// Display ten contacts and select a contact
var contacts = context.Contacts.Take(10);
foreach (var c in contacts)
Console.WriteLine(c.ContactID);
Console.WriteLine("Select a customer:");
Int32 contactID = Convert.ToInt32(Console.ReadLine());
// Get a specified customer by contact ID.
var contact = context.Contacts.Where(c => c.ContactID == contactID).FirstOrDefault();
// If lazy loading was not enabled no SalesOrderHeaders would be loaded for the contact.
foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
{
Console.WriteLine("SalesOrderID: {0} Order Date: {1} ",
order.SalesOrderID, order.OrderDate);
}
}
}
}
另请参见
任务
如何:使用查询路径调整结果(实体框架)
如何:显式加载相关对象(实体框架)