HOW TO:在物件狀態變更時執行商務邏輯

本主題示範如何在物件內容內之實體變更狀態時執行商務邏輯。 下列範例顯示如何處理 ObjectStateManagerChanged 事件,該事件是在實體透過刪除或中斷連結方法來離開內容,或是透過查詢或加入與附加方法來進入內容時發生。

本主題的範例根據 Adventure Works Sales Model。若要執行此主題中的程式碼,您必須已經將 Adventure Works Sales Model 加入到專案中,並設定您的專案使用 Entity Framework。如需詳細資訊,請參閱 HOW TO:使用實體資料模型精靈 (Entity Framework)HOW TO:手動設定 Entity Framework 專案HOW TO:手動設定 Entity Framework 專案

範例

下列範例示範如何註冊 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);
}

另請參閱

工作

HOW TO:在純量屬性變更期間執行商務邏輯 (Entity Framework)
HOW TO:在關聯變更期間執行商務邏輯
HOW TO:在儲存變更時執行商務邏輯 (Entity Framework)