Database Reference
In-Depth Information
The following is the output from the code in Listing 6-33:
Members of our club
===================
Steven Keller is a Teen member, phone: unavailable
Margret Jones is an Adult member, phone: 913 294-6059
Roland Park is a Senior member, phone: 816 353-4458
It is important to note here that no design time, or even runtime checking, is done to verify the ages for the
derived types. It is entirely possible to create an instance of the Teen type and set the age property to 74—clearly not a
teen. On the retrieval side, however, this row will be materialized as a Senior member—a situation likely to offend our
Teen member.
We can introduce validation before changes are committed to the data store. To do this, register for the
SavingChanges event when the context is created. We wire this event to our code that performs the validation.
This code is shown in Listing 6-34.
Listing 6-34. Handling Validation in the SavingChanges Event
public partial class EF6RecipesContext
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(Validate);
}
public void Validate(object sender, EventArgs e)
{
var entities = this.ObjectStateManager
.GetObjectStateEntries(EntityState.Added |
EntityState.Modified)
.Select(et => et.Entity as Member);
foreach (var member in entities) {
if (member is Teen && member.Age > 19) {
throw new ApplicationException("Entity validation failed");
}
else if (member is Adult && (member.Age < 20 || member.Age >= 55)) {
throw new ApplicationException("Entity validation failed");
}
else if (member is Senior && member.Age < 55) {
throw new ApplicationException("Entity validation failed");
}
}
}
}
In Listing 6-34, when SaveChanges() is called, our Validate() method checks each entity that has either been
added or modified. For each of these, we verify that the age property is appropriate for the type of the entity. When we
find a validation error, we simply throw an exception.
We have several recipes in Chapter 12 that focus on handling events and validating objects before they are
committed to the database.
 
Search WWH ::




Custom Search