如何:当对象状态发生更改时执行业务逻辑

本主题介绍如何在对象上下文中的实体状态更改后执行业务逻辑。 下面的示例介绍如何处理 ObjectStateManagerChanged 事件,该事件在实体通过删除或分离方法离开上下文,或通过查询或添加并附加方法进入上下文时发生。

本主题中的示例基于 Adventure Works 销售模型。若要运行本主题中的代码,则必须已经将 Adventure Works 销售模型添加到了您的项目中,并且已经将项目配置为使用实体框架。有关更多信息,请参见如何:使用实体数据模型向导(实体框架)如何:手动配置实体框架项目如何:手动定义实体数据模型(实体框架)

示例

下面的示例演示如何注册 ObjectStateManagerChanged 事件。 此事件在对象进入或离开上下文时发生。 在此示例中,一个匿名方法将传递给委托。 此外,还可以定义事件处理方法,然后将该方法的名称传递给委托。 只要该事件被触发,匿名方法将显示对象的状态。

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

另请参见

任务

如何:在标量属性更改过程中执行业务逻辑(实体框架)
如何:在关联更改过程中执行业务逻辑
如何:在保存更改时执行业务逻辑(实体框架)