ObjectContext.SavingChanges 이벤트

정의

변경 내용이 데이터 소스에 저장될 때 발생합니다.

public:
 event EventHandler ^ SavingChanges;
public event EventHandler SavingChanges;
member this.SavingChanges : EventHandler 
Public Custom Event SavingChanges As EventHandler 

이벤트 유형

예제

다음은 엔터티 상태 유효성 검사를 수행하는 이벤트에 대한 SavingChanges 처리기를 등록하는 예제입니다.

public class AdventureWorksProxy
{
    // Define the object context to be provided.
    private AdventureWorksEntities contextProxy =
        new AdventureWorksEntities();

    public AdventureWorksProxy()
    {
        // When the object is initialized, register the
        // handler for the SavingChanges event.
        contextProxy.SavingChanges
            += new EventHandler(context_SavingChanges);
    }

    // Method that provides an object context.
    public AdventureWorksEntities Context
    {
        get
        {
            return contextProxy;
        }
    }

    // SavingChanges event handler.
    private void context_SavingChanges(object sender, EventArgs e)
    {
        // Ensure that we are passed an ObjectContext
        ObjectContext context = sender as ObjectContext;
        if (context != null)
        {

            // Validate the state of each entity in the context
            // before SaveChanges can succeed.
            foreach (ObjectStateEntry entry in
                context.ObjectStateManager.GetObjectStateEntries(
                EntityState.Added | EntityState.Modified))
            {
                // Find an object state entry for a SalesOrderHeader object.
                if (!entry.IsRelationship && (entry.Entity.GetType() == typeof(SalesOrderHeader)))
                {
                    SalesOrderHeader orderToCheck = entry.Entity as SalesOrderHeader;

                    // Call a helper method that performs string checking
                    // on the Comment property.
                    string textNotAllowed = Validator.CheckStringForLanguage(
                        orderToCheck.Comment);

                    // If the validation method returns a problem string, raise an error.
                    if (!string.IsNullOrEmpty(textNotAllowed))
                    {
                        throw new ArgumentException(String.Format("Changes cannot be "
                            + "saved because the {0} '{1}' object contains a "
                            + "string that is not allowed in the property '{2}'.",
                            entry.State, "SalesOrderHeader", "Comment"));
                    }
                }
            }
        }
    }
}

설명

이벤트는 SavingChanges 에 대한 작업이 시작될 SaveChanges 때 발생합니다 ObjectContext. 이 이벤트는 일반적으로 새 값이 데이터베이스에 기록되기 전에 변경된 개체의 유효성을 검사하는 데 사용됩니다.

적용 대상

추가 정보