Share via


Cómo: Ejecutar la lógica de negocios durante los cambios de asociación

En este tema se muestra cómo ejecutar la lógica de negocios cuando una asociación entre entidades cambia.

El ejemplo de este tema se basa en el modelo AdventureWorks Sales. Para ejecutar el código de este tema, debe haber agregado el modelo AdventureWorks Sales al proyecto y haber configurado el proyecto para que use Entity Framework. Para obtener más información, vea Cómo: Usar el Asistente para Entity Data Model (Entity Framework) o Cómo: Configurar manualmente un proyecto de Entity Framework y Cómo: Definir manualmente un modelo Entity Data Model (Entity Framework).

También debe agregar la siguiente instrucción using (Imports en Visual Basic) al código:

Imports System.ComponentModel
using System.ComponentModel;

Ejemplo

Este ejemplo amplía el ejemplo del tema Cómo: Usar un objeto EntityReference para cambiar las relaciones entre los objetos (Entity Framework). Este ejemplo muestra cómo comprobar el estado del pedido cuando la dirección de envío cambia; esto se realiza controlando el evento AssociationChanged sobre la referencia EntityReference para el objeto Address que representa la dirección de envío. Si el estado del pedido es mayor que 3, no se puede cambiar el pedido y se produce una excepción. El delegado se define en el constructor para la clase parcial SalesOrderHeader y el controlador para este evento también se implementa en esta clase parcial. De esta forma se garantiza que el estado del pedido se comprueba siempre que la dirección de envío se cambia para un pedido.

También puede llamar a los métodos OnPropertyChanged y OnPropertyChanging en este evento para generar los eventos PropertyChanged y PropertyChanging, respectivamente. Estos eventos notifican a los controles del cliente los cambios en la asociación.

Para validar los cambios en el otro extremo de la relación SalesOrderHeader-Address, se puede usar una técnica similar para registrar el evento AssociationChanged en la colección EntityCollection de objetos SalesOrderHeader relacionados con una dirección de envío.

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");
        }
    }
}

Vea también

Tareas

Cómo: Ejecutar la lógica de negocios cuando el estado del objeto cambia
Cómo: Ejecutar la lógica empresarial durante los cambios de propiedades escalares (Entity Framework)
Cómo: Ejecutar la lógica de negocios al guardar los cambios (Entity Framework)