Procedura: eseguire la logica di business quando vengono modificate le associazioni

In questo argomento viene illustrato come eseguire la logica di business quando viene modificata un'associazione tra entità.

L'esempio incluso in questo argomento è basato sul modello Sales di AdventureWorks. Per eseguire il codice incluso in questo argomento, è necessario avere già aggiunto il modello Sales di AdventureWorks al progetto e avere configurato il progetto per l'utilizzo di Entity Framework. Per ulteriori informazioni, vedere Procedura: utilizzare la Procedura guidata Entity Data Model (Entity Framework) o Procedura: configurare manualmente un progetto di Entity Framework e Procedura: definire manualmente un modello EDM (Entity Framework).

È inoltre necessario aggiungere al codice l'istruzione using (Imports in Visual Basic) seguente:

Imports System.ComponentModel
using System.ComponentModel;

Esempio

Questo esempio estende l'esempio incluso nell'argomento Procedura: utilizzare un elemento EntityReference per modificare le relazioni tra oggetti (Entity Framework). In questo esempio viene illustrato come controllare lo stato dell'ordine quando l'indirizzo di spedizione viene modificato gestendo l'evento AssociationChanged su EntityReference per l'oggetto Address che rappresenta l'indirizzo di spedizione. Se lo stato dell'ordine è maggiore di 3, l'ordine non può essere modificato e viene generata un'eccezione. Il delegato è definito nel costruttore per la classe parziale SalesOrderHeader e anche il gestore per questo evento è implementato in questa classe parziale. In questo modo si ha la certezza che lo stato dell'ordine venga controllato ogni volta che per un ordine viene modificato l'indirizzo di spedizione.

È inoltre possibile chiamare i metodi OnPropertyChanging e OnPropertyChanged in questo evento per generare rispettivamente gli eventi PropertyChanging e PropertyChanged. Questi eventi notificano le modifiche dell'associazione ai controlli client.

Per convalidare le modifiche all'altra entità finale della relazione SalesOrderHeader-Address, è possibile utilizzare una tecnica simile per registrare l'evento AssociationChanged su un insieme EntityCollection di oggetti SalesOrderHeader correlati a un indirizzo di spedizione.

Partial Public Class SalesOrderHeader
    ' SalesOrderHeader default constructor. 
    Public Sub New()
        ' Register the handler for changes to the 
        ' shipping address (Address1) reference. 
        AddHandler Me.AddressReference.AssociationChanged, AddressOf ShippingAddress_Changed
    End Sub

    ' AssociationChanged handler for the relationship 
    ' between the order and the shipping address. 
    Private Sub ShippingAddress_Changed(ByVal sender As Object, ByVal e As CollectionChangeEventArgs)
        ' Check for a related reference being removed. 
        If e.Action = CollectionChangeAction.Remove Then
            ' Check the order status and raise an exception if 
            ' the order can no longer be changed. 
            If Me.Status > 3 Then
                Throw New InvalidOperationException("The shipping address cannot " & _
                                                    "be changed because the order has either " & _
                                                    "already been shipped or has been cancelled.")
            End If
            ' Call the OnPropertyChanging method to raise the PropertyChanging event. 
            ' This event notifies client controls that the association is changing. 
            Me.OnPropertyChanging("Address1")
        ElseIf e.Action = CollectionChangeAction.Add Then
            ' Call the OnPropertyChanged method to raise the PropertyChanged event. 
            ' This event notifies client controls that the association has changed. 
            Me.OnPropertyChanged("Address1")
        End If
    End Sub
End Class
public partial class SalesOrderHeader
{
    // SalesOrderHeader default constructor.
    public SalesOrderHeader()
    {
        // Register the handler for changes to the 
        // shipping address (Address1) reference.
        this.AddressReference.AssociationChanged
            += new CollectionChangeEventHandler(ShippingAddress_Changed);
    }

    // AssociationChanged handler for the relationship 
    // between the order and the shipping address.
    private void ShippingAddress_Changed(object sender,
        CollectionChangeEventArgs e)
    {
        // Check for a related reference being removed. 
        if (e.Action == CollectionChangeAction.Remove)
        {
            // Check the order status and raise an exception if 
            // the order can no longer be changed.
            if (this.Status > 3)
            {
                throw new InvalidOperationException(
                    "The shipping address cannot "
                + "be changed because the order has either "
                + "already been shipped or has been cancelled.");
            }
            // Call the OnPropertyChanging method to raise the PropertyChanging event.
            // This event notifies client controls that the association is changing.
            this.OnPropertyChanging("Address1");
        }
        else if (e.Action == CollectionChangeAction.Add)
        {
            // Call the OnPropertyChanged method to raise the PropertyChanged event.
            // This event notifies client controls that the association has changed.
            this.OnPropertyChanged("Address1");
        }
    }
}

Vedere anche

Attività

Procedura: eseguire la logica di business al momento della modifica dello stato dell'oggetto (Entity Framework)
Procedura: eseguire la logica di business quando vengono modificate le proprietà scalari (Entity Framework)
Procedura: eseguire la logica di business al momento del salvataggio delle modifiche (Entity Framework)