Database Reference
In-Depth Information
12-8. Retrieving the Original Value of a Property
Problem
You want to retrieve the original value of a property before the entity is saved to the database.
Solution
Let's say that you have a model (see Figure 12-11 ) representing an Employee, and part of this entity includes the
employee's salary. You have a business rule that an employee's salary cannot be increased by more than 10 percent.
To enforce this rule, you want to check the new salary against the original salary for increases in excess of 10 percent.
You want to do this check just before the entity is saved to the database.
Figure 12-11. An Employee entity with the employee's salary
To verify that a salary increase does not exceed 10 percent as required by our business rule, we override the
SaveChanges event. In the overridden event, we retrieve the current and original values. If the new value is more than
110 percent of the original value, we throw an exception. This exception, of course, causes the saving of the entity to
fail. The code in Listing 12-8 provides the details.
Listing 12-8. Overriding the SaveChanges Event to Enforce the Business Rule
class Program
{
static void Main(string[] args)
{
RunExample();
}
static void RunExample()
{
using (var context = new EFRecipesEntities())
{
var emp1 = new Employee { Name = "Roger Smith", Salary = 108000M };
var emp2 = new Employee { Name = "Jane Hall", Salary = 81500M };
context.Employees.Add(emp1);
context.Employees.Add(emp2);
context.SaveChanges();
emp1.Salary = emp1.Salary * 1.5M;
try
 
Search WWH ::




Custom Search