Databases Reference
In-Depth Information
LISTING 9.2
Making ObjectContext Available to Validation Methods
public partial class UnleashedObjectContext
{
private void Validate(ObjectStateEntry stateEntry)
{
object entity = stateEntry.Entity;
var items = new Dictionary<object, object>();
items[typeof(ObjectStateEntry)] = stateEntry;
items[typeof(ObjectContext)] = this;
var context = new ValidationContext(entity, null, items);
var results = new List<ValidationResult>();
if (!Validator.TryValidateObject(entity, context, results, true))
ThrowValidationException(entity, results);
}
}
Entity Deletion Rules
Because persistence validation rules are designed to ensure that entities are
saved
in a valid
state, most of them are not applicable and should not be evaluated when entities are
deleted
. For example, suppose you have a requirement to prevent deletion of orders after
they have been submitted. Even though you implemented a custom validation method
that requires the
OrderDate
not to be in the past, from deletion standpoint, you only care
about the value of the
OrderStatus
property. Evaluating the validation rules for the
OrderDate
and other properties would prevent deletion of an entity that should have
otherwise been allowed.
Because persistence validation rules are not applicable to entity deletion, the
BeforeSaveChanges
method of the
UnleashedObjectContext
class validates only added
and modified entities. On the other hand, the
ISavableObject
interface is not bound by
the same constraints as the validation logic. The
UnleashedObjectContext
class calls the
BeforeSave method of all entities, including the deleted ones, which allows you to imple-
ment validation of entity deletion without introducing conflicts with the validation of
entity persistence. Here is how you can implement the
BeforeSave
method in the
Order
class to allow deleting only
Draft
orders:
partial class Order: ISavableObject
{
public void BeforeSave(ObjectStateEntry stateEntry)
{
if (stateEntry.State == EntityState.Deleted &&
this.OrderStatus != (byte)DataModel.OrderStatus.Draft)