방법: 개체 상태가 변경될 때 비즈니스 논리 실행(Entity Framework)

이 항목에서는 개체 컨텍스트 내에서 엔터티 상태가 변경될 때 비즈니스 논리를 실행하는 방법을 보여 줍니다. 다음 예제에서는 엔터티가 삭제 또는 분리 메서드를 통해 컨텍스트에서 나갈 때 또는 쿼리나 추가 및 연결 메서드를 통해 컨텍스트에 들어갈 때 발생하는 ObjectStateManagerChanged 이벤트를 처리하는 방법을 보여 줍니다.

이 항목의 예제는 Adventure Works Sales 모델을 기반으로 합니다. 이 항목의 코드를 실행하려면 프로젝트에 Adventure Works Sales 모델을 추가하고 프로젝트에서 Entity Framework를 사용하도록 구성해야 합니다. 자세한 내용은 방법: 엔터티 데이터 모델 마법사 사용(Entity Framework) 또는 방법: Entity Framework 프로젝트 수동 구성방법: 엔터티 데이터 모델 수동 정의(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);
}

참고 항목

작업

방법: 스칼라 속성 변경 중 비즈니스 논리 실행(Entity Framework)
방법: 연결 변경 중 비즈니스 논리 실행
방법: 변경된 내용을 저장할 때 비즈니스 논리 실행(Entity Framework)