Database Reference
In-Depth Information
Figure 12-16. A model for customers and their orders
There are certain business rules around customers and their orders. You want to make sure that these rules are
checked before an order is saved to the database. Let's say that you have the following rules:
The order date on an order must be after the current date.
The ship date on an order must be after the order date.
An order cannot be shipped unless it is in an “Approved” status.
If an order amount is over $5,000, there is no shipping charge.
An order that has shipped cannot be deleted.
To check if changes to an entity violates any of these rules, we'll define an IValidatable interface that has just
one method: Validate() . Any of our entity types can implement this interface. For this example, we'll show the
implementation for the SalesOrder entity. We'll handle the SavingChanges event and call Validate() on all entities
that implement IValidator. This will allow us to intercept and validate entities before they are saved to the database.
The code in Listing 12-13 provides the details.
Listing 12-13. Validating SaleOrder Entities in the SavingeChanges Event
class Program
{
static void Main(string[] args)
{
RunExample();
}
static void RunExample()
{
// bad order date
using (var context = new EFRecipesEntities())
{
var customer = new Customer { Name = "Phil Marlowe" };
var order = new SalesOrder { OrderDate = DateTime.Parse("3/12/18"),
 
Search WWH ::




Custom Search