How to: Execute Business Logic During Scalar Property 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 your own custom business logic to perform custom actions when changes are made to generated properties. Entity Data Model Tools generate data classes that represent entities in a conceptual model. Although these generated classes should not be modified directly, for each generated property, the tools also generate a pair of partial methods named OnPropertyChanging and OnPropertyChanged, where Property is the property name. These methods are called by the Entity Framework before and after a property is changed, and you can extend these methods in partial data classes to implement custom code. 

Cc716747.note(en-us,VS.110).gifNote:
If the object-layer code was generated with a text template other than a default text template, the partial methods might not have been generated.

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.

To implement custom validation for property changes

  1. In your project, define a custom partial class for each data class to validate.

  2. In this partial class, define one or both of the following methods, where Property is the name of the property to validate:

    • OnPropertyChanging - include code to execute before the change occurs, such as property validation. The value parameter is the value to which the property is changing. Implement this method to validate a property change before it occurs. To prevent the change from being made, you must throw an exception.

    • OnPropertyChanged - include code to execute after the change occurs, such as logging the change.

Example

This example checks the value of SalesOrderHeader.Status to ensure that the order can be changed before a change is made to SalesOrderDetail.OrderQty and the pending change is logged to a file. This action is performed in the OnOrderQtyChanging partial method. If the change cannot be made, an exception is raised. Then, after the change is made successfully, the SalesOrderHeader.Status value is reset to 1 and the completed change is logged. These actions are performed in the OnOrderQtyChanged partial method.

See Also

Show: