EntityCollection<TEntity>.Load(MergeOption) Método
Definição
Carrega os objetos relacionados na coleção, usando a opção de mesclagem especificada.Loads related objects into the collection, using the specified merge option.
public:
override void Load(System::Data::Objects::MergeOption mergeOption);
public override void Load (System.Data.Objects.MergeOption mergeOption);
override this.Load : System.Data.Objects.MergeOption -> unit
Public Overrides Sub Load (mergeOption As MergeOption)
Parâmetros
- mergeOption
- MergeOption
Especifica como os objetos nesta coleção devem ser mesclados com os objetos que podem ter sido retornados de consultas anteriores com o mesmo ObjectContext.Specifies how the objects in this collection should be merged with the objects that might have been returned from previous queries against the same ObjectContext.
Exemplos
Este exemplo se baseia no modelo de vendas da Adventure Works.This example is based on the Adventure Works Sales Model. Para executar o código neste exemplo, você já deve ter adicionado o modelo de vendas AdventureWorks ao seu projeto e configurado seu projeto para usar o Entity Framework.To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. Para fazer isso, conclua os procedimentos em como configurar manualmente um projeto de Entity Framework e como definir manualmente o modelo e os arquivos de mapeamento.To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files.
Este exemplo carrega os SalesOrderHeader objetos relacionados para a Contact entidade.This example loads the related SalesOrderHeader objects for the Contact entity.
// Specify the customer ID.
int contactID = 4332;
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
context.ContextOptions.LazyLoadingEnabled = false;
// Get a specified customer by contact ID.
var contact =
(from c in context.Contacts
where c.ContactID == contactID
select c).First();
// Load the orders for the customer explicitly.
if (!contact.SalesOrderHeaders.IsLoaded)
{
contact.SalesOrderHeaders.Load();
}
foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
{
// Load the items for the order if not already loaded.
if (!order.SalesOrderDetails.IsLoaded)
{
order.SalesOrderDetails.Load();
}
Console.WriteLine(String.Format("PO Number: {0}",
order.PurchaseOrderNumber));
Console.WriteLine(String.Format("Order Date: {0}",
order.OrderDate.ToString()));
Console.WriteLine("Order items:");
foreach (SalesOrderDetail item in order.SalesOrderDetails)
{
Console.WriteLine(String.Format("Product: {0} "
+ "Quantity: {1}", item.ProductID.ToString(),
item.OrderQty.ToString()));
}
}
}
' Specify the customer ID.
Dim contactID As Integer = 4332
Using context As New AdventureWorksEntities()
context.ContextOptions.LazyLoadingEnabled = False
' Get a specified customer by contact ID.
Dim contact = (From c In context.Contacts
Where c.ContactID = contactID
Select c).First()
' Load the orders for the customer explicitly.
If Not contact.SalesOrderHeaders.IsLoaded Then
contact.SalesOrderHeaders.Load()
End If
For Each order As SalesOrderHeader In contact.SalesOrderHeaders
' Load the items for the order if not already loaded.
If Not order.SalesOrderDetails.IsLoaded Then
order.SalesOrderDetails.Load()
End If
Console.WriteLine(String.Format("PO Number: {0}", order.PurchaseOrderNumber))
Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
Console.WriteLine("Order items:")
For Each item As SalesOrderDetail In order.SalesOrderDetails
Console.WriteLine(String.Format("Product: {0} Quantity: {1}", _
item.ProductID.ToString(), item.OrderQty.ToString()))
Next
Next
End Using
Comentários
Esse método chama o RelatedEnd.ValidateLoad método interno antes de carregar a coleção, o que valida que uma chamada para Load tem as condições corretas.This method calls the internal RelatedEnd.ValidateLoad method before loading the collection, which validates that a call to Load has the correct conditions. O RelatedEnd.ValidateLoad método verifica se:The RelatedEnd.ValidateLoad method checks that:
- Existe uma válida ObjectContext .A valid ObjectContext exists.
- A entidade não está em um Deleted estado.The entity isn't in a Deleted state.
- MergeOption for Load deve ser NoTracking If e only se a entidade de origem tiver sido NoTracking .MergeOption for Load must be NoTracking if and only if the source entity was NoTracking. Se a entidade de origem foi recuperada com qualquer outra MergeOption , o Load MergeOption pode ser qualquer coisa, mas NoTracking (por exemplo, a entidade poderia ter sido carregada com OverwriteChanges e a Load opção pode ser AppendOnly ).If the source entity was retrieved with any other MergeOption, the Load MergeOption can be anything but NoTracking (for example, the entity could have been loaded with OverwriteChanges and the Load option can be AppendOnly).
- Se
mergeOptionfor NoTracking , não é Load chamado em uma entidade já carregada e não Load é chamado em um não vazio, não rastreado RelatedEnd .IfmergeOptionis NoTracking, Load isn't called on an already loaded entity and Load isn't called on a non-empty, not-tracked RelatedEnd.
Quando os objetos na coleção já estão carregados no ObjectContext , o Load método impõe o MergeOption especificado pelo mergeOption parâmetro.When objects in the collection are already loaded into the ObjectContext, the Load method enforces the MergeOption specified by the mergeOption parameter. Para obter mais informações, consulte resolução de identidade, gerenciamento de estado e controle de alterações.For more information, see Identity Resolution, State Management, and Change Tracking.
Para carregar explicitamente objetos relacionados, você deve chamar o Load método na extremidade relacionada retornada pela propriedade de navegação.To explicitly load related objects, you must call the Load method on the related end returned by the navigation property. Para uma relação um-para-muitos, chame o Load método em EntityCollection<TEntity> .For a one-to-many relationship, call the Load method on EntityCollection<TEntity>. Para uma relação um-para-um, ligue para Load EntityReference<TEntity> .For a one-to-one relationship, call the Load on EntityReference<TEntity>. Isso carrega os dados do objeto relacionado no contexto do objeto.This loads the related object data into the object context. Você pode enumerar por meio da coleção de resultados retornados usando um foreach loop ( For Each...Next em Visual Basic) e chamar condicionalmente o Load método em EntityReference<TEntity> e EntityCollection<TEntity> as propriedades de cada entidade nos resultados.You can enumerate through the collection of returned results using a foreach loop (For Each...Next in Visual Basic) and conditionally call the Load method on EntityReference<TEntity> and EntityCollection<TEntity> properties for each entity in the results.
O Load método carrega objetos relacionados da fonte de dados, seja ou IsLoaded não true .The Load method loads related objects from the data source whether or not IsLoaded is true.
Observação
Quando você chama o Load método durante uma foreach Enumeração (C#) ou For Each (Visual Basic), serviços de objeto tenta abrir um novo leitor de dados.When you call the Load method during a foreach (C#) or For Each (Visual Basic) enumeration, Object Services tries to open a new data reader. Essa operação falhará, a menos que você tenha habilitado vários conjuntos de resultados ativos especificando multipleactiveresultsets=true na cadeia de conexão.This operation will fail unless you have enabled multiple active results sets by specifying multipleactiveresultsets=true in the connection string. Você também pode carregar o resultado da consulta em uma List<T> coleção.You can also load the result of the query into a List<T> collection. Isso fecha o leitor de dados e permite que você enumere a coleção para carregar objetos referenciados.This closes the data reader and enables you to enumerate over the collection to load referenced objects.
O EntityCollection<TEntity>.Load método é sincronizado com o EntityReference<TEntity>.Load método.The EntityCollection<TEntity>.Load method is synchronized with the EntityReference<TEntity>.Load method.