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 操作の開始時に発生します。 通常、このイベントは、新しい値がデータベースに書き込まれる前に、変更されたオブジェクトを検証するために使用されます。

適用対象

こちらもご覧ください