How to: Execute Business Logic When Saving Changes

[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

The Entity Framework enables you to execute custom business logic before changes are saved to the database. The SavingChanges event is raised before a SaveChanges operation is processed. Handle this event to implement custom business logic before changes are saved to the database. Starting with the .NET Framework version 4 the SaveChanges method is virtual. This means that you can override this method directly instead of subscribing to the SavingChanges event.

The examples in this topic show how to override the SaveChanges method and handle the SavingChanges event to validate changed objects in an object context before those changes are persisted to the database.

The example in this topic is based on the Adventure Works Sales Model. To run the code in this example, you must have already added the AdventureWorks Sales Model to your project and configured your project to use the Entity Framework. To do this, complete the procedures in How to: Manually Configure an Entity Framework Project and How to: Manually Define the Model and Mapping Files

The first example shows how to override the SaveChanges method in the custom object context class. The second example shows how to use OnContextCreated to register a handler for the SavingChanges event in an instance of ObjectContext. The third example shows how to handle this event in a proxy class that derives from ObjectContext. The fourth example shows code that makes changes to objects using the proxy class from the second example and then calls SaveChanges.


In this example, the SaveChanges method is overridden to enable you to validate objects that have an Added or Modified EntityState. This example is based on the custom object context defined in How to: Define a Custom Object Context.

In this example, the OnContextCreated method is defined as a partial method of AdventureWorksEntities. The handler for the SavingChanges event is defined in this partial method. The event handler verifies that the calling code has not added any inappropriate text in the SalesOrderHeader.Comment property before the changes can be persisted. If the string checking algorithm (not shown) finds any problems, an exception is raised.

In this example, an instance of the AdventureWorksProxy class is used to change the Comment property of a SalesOrderHeader object. When SaveChanges is called on the instance of ObjectContext provided by the AdventureWorksProxy class, the validation code from the previous example is run.

This example makes changes to objects in the proxy class that derives from ObjectContext and then calls SaveChanges. This example is used to invoke the event handling demonstrated in the previous example.

See Also