Database Reference
In-Depth Information
if (this.Amount > 5000M && this.ShippingCharge != 0)
{
throw new ApplicationException(
"Orders over $5000 ship for free");
}
}
else if (entry.State == EntityState.Deleted)
{
if (this.Shipped.Value)
throw new ApplicationException(
"Shipped orders cannot be deleted");
}
}
}
Following is the output of the code in Listing 12-13:
OrderDate cannot be after the current date
ShippedDate cannot be before OrderDate
Order cannot be shipped unless it is Approved
Orders over $5000 ship for free
Shipped orders cannot be deleted
How It Works
When you call SaveChanges() , Entity Framework raises the SavingChanges event before it saves the object changes
to the database. We implemented the partial method OnContextCreated() so that we can wire in a handler for this
event. When SavingChanges is raised, we handle the event by calling the Validate() method on every entity that
implements the IValidator interface. We've shown an implementation of this interface that supports our business
rules. If you have business rules for other entity types in your model, you could implement the IValidator interface
for them.
Best Practice
Business rules in many applications almost always change over time. Industry or government regulation changes,
continuous process improvement programs, evolving fraud prevention, and many other factors influence the
introduction of new business rules as well as changes to existing rules. It's a best practice to organize your code base
so that the concerns around business rule validation and enforcement are more easily maintained. Often, this means
keeping all of this code in a separate assembly or in a separate folder in the project. Defining and implementing
interfaces, such as the IValidator interface in this recipe, help to ensure that business rules validation is uniformly
applied.
 
Search WWH ::




Custom Search