Share via


Procédure : modifier les relations entre des entités POCO (Entity Framework)

Lorsque la création d'objets proxy est désactivée ou qu'une entité POCO est créée sans son objet proxy, vous devez faire appel à la méthode DetectChanges au niveau de l'objet ObjectContext pour synchroniser les modifications avec l'objet ObjectStateManager. En plus de détecter les modifications dans les propriétés scalaires, cette méthode détecte les modifications dans les relations, y compris l'ajout, la suppression ou la modification d'un objet connexe. Pour plus d'informations, consultez Suivi des modifications dans les entités POCO (Entity Framework). Dans la mesure où la méthode SaveChanges appelle DetectChanges, vous n'avez pas à appeler explicitement DetectChanges si vous n'avez pas besoin d'une synchronisation immédiate des relations.

L'exemple de cette rubrique utilise les classes de données personnalisées POCO définies dans Procédure : définir des entités POCO (Entity Framework) et un modèle de données basé sur AdventureWorks défini dans Procédure : personnaliser des fichiers de modèle et de mappage pour utiliser des objets personnalisés (Entity Framework).

Exemple

Cet exemple remplace le contact actuel pour une commande (« order ») par un autre contact. La méthode DetectChanges est appelée par la méthode SaveChanges avant l'enregistrement des modifications dans la source de données.

Using context As New POCOAdventureWorksEntities()
    ' Disable proxy object creation. 
    context.ContextOptions.ProxyCreationEnabled = False
    Try
        ' Define the order and new address IDs. 
        Dim orderId As Integer = 43659
        Dim differentContactID As Integer = 5

        Dim order As Order = context.Orders.Include("Contact").Where(Function(o) o.SalesOrderID = orderId).First()

        ' Get contact to change to. 
        Dim differentContact As Contact = context.Contacts.First(Function(c) c.ContactID = differentContactID)

        ' The current contact. 
        Console.WriteLine("Original Contact Name: {0}", order.Contact.FirstName)

        ' The Entity Framework takes care of setting the other end of the relationship 
        ' when you call DetectChanges or SaveChanges (which calls DetectChanges). 
        ' However, there are scenarios when you are not working with ObjectContext 
        ' and will want to fix both ends of the relationship yourself 
        ' (for example, when working with disconnected objects). 

        ' Change the current ContactID to the new ContactID. 
        order.ContactID = differentContact.ContactID

        ' Because the change tracking is not enabled 
        ' The state manager will not be updated untill DetectChanges is called. 
        ' If context.ContextOptions.ProxyCreationEnabled was set to true (which is the default) 
        ' The changes would be synchronized righ away. 
        Console.WriteLine("The contact was updated, but DetectChanges was not yet called. ")
        Console.WriteLine("Contact Name: {0}", order.Contact.FirstName)
        context.DetectChanges()
        Console.WriteLine("After DetectChanges was called. Contact Name: {0}", order.Contact.FirstName)

        ' Call save the changes, which calls DetectChanges. 
        context.SaveChanges()
    Catch ex As UpdateException
        Console.WriteLine(ex.ToString())
    Catch ex As InvalidOperationException
        Console.WriteLine(ex.ToString())
    End Try
End Using
using (POCOAdventureWorksEntities context =
        new POCOAdventureWorksEntities())
{
    // Disable proxy object creation.
    context.ContextOptions.ProxyCreationEnabled = false;
    try
    {
        // Define the order and new address IDs.
        int orderId = 43659;
        int differentContactID = 5;

        Order order =
               context.Orders.Include("Contact")
               .Where(o => o.SalesOrderID == orderId).First();

        // Get contact to change to.
        Contact differentContact = context.Contacts.
            First(c => c.ContactID == differentContactID);
        
        // The current contact.
        Console.WriteLine("Original Contact Name: {0}", order.Contact.FirstName);

        // The Entity Framework takes care of setting the other end of the relationship
        // when you call DetectChanges or SaveChanges (which calls DetectChanges).
        // However, there are scenarios when you are not working with ObjectContext
        // and will want to fix both ends of the relationship yourself
        // (for example, when working with disconnected objects). 

        // Change the current ContactID to the new ContactID.
        order.ContactID = differentContact.ContactID;

        // Because the change tracking is not enabled
        // The state manager will not be updated untill DetectChanges is called.
        // If context.ContextOptions.ProxyCreationEnabled was set to true (which is the default)
        // The changes would be synchronized righ away. 
        Console.WriteLine("The contact was updated, but DetectChanges was not yet called. ");
        Console.WriteLine("Contact Name: {0}", order.Contact.FirstName);
        context.DetectChanges();
        Console.WriteLine("After DetectChanges was called. Contact Name: {0}",
            order.Contact.FirstName);

        // Call save the changes, which calls DetectChanges.
        context.SaveChanges();
    }
    catch (UpdateException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    catch (InvalidOperationException ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Voir aussi

Concepts

Utilisation d'entités POCO (Entity Framework)