How to: Execute Business Logic When the Object State Changes

This topic shows how to execute business logic when an entity changes state within the object context. The following example shows how to handle the ObjectStateManagerChanged event, which occurs when entities leave the context through delete or detach methods or enter the context through queries or add and attach methods.

The example in this topic is based on the Adventure Works Sales Model. To run the code in this topic, you must have already added the Adventure Works Sales Model to your project and configured your project to use the Entity Framework. For more information, see How to: Use the Entity Data Model Wizard (Entity Framework) or How to: Manually Configure an Entity Framework Project and How to: Manually Define an Entity Data Model (Entity Framework).

Example

The following example demonstrates how to register for the ObjectStateManagerChanged event. This event occurs when an object enters or leaves the context. In this example, an anonymous method is passed to the delegate. Alternatively, you can define the event handling method and then pass its name to the delegate. The anonymous method displays the status of the object whenever the event is triggered.

int productID = 3;
string productName = "Flat Washer 10";
string productNumber = "FW-5600";
Int16 safetyStockLevel = 1000;
Int16 reorderPoint = 750;

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // The ObjectStateManagerChanged event is raised whenever 
    // an entity leaves or enters the context. 
    context.ObjectStateManager.ObjectStateManagerChanged += (sender, e) =>
    {
        Console.WriteLine(string.Format(
        "ObjectStateManager.ObjectStateManagerChanged | Action:{0} Object:{1}"
        , e.Action
        , e.Element));
    };


    // When an entity is queried for we get an added event.
    var product =
            (from p in context.Products
             where p.ProductID == productID
             select p).First();

    // Create a new Product.
    Product newProduct = Product.CreateProduct(0,
        productName, productNumber, false, false, safetyStockLevel, reorderPoint,
        0, 0, 0, DateTime.Today, Guid.NewGuid(), DateTime.Today);

    // Add the new object to the context.
    // When an entity is added we also get an added event.
    context.Products.AddObject(newProduct);

    // Delete the object from the context.
    //Deleting an entity raises a removed event.
    context.Products.DeleteObject(newProduct);
}

See Also

Tasks

How to: Execute Business Logic During Scalar Property Changes
How to: Execute Business Logic During Association Changes
How to: Execute Business Logic When Saving Changes