Databases Reference
In-Depth Information
FIGURE 8.10
Multiple errors correctly reported on a Dynamic Data web page.
Sometimes validating current state of an entity is insufficient. Consider the Order entity
and its
OrderStatus
property, which indicates whether an order has been submitted, paid,
or fulfilled. It would be bad if someone could change the status of a fulfilled order back to
paid and receive a second product free. Here is a code example that illustrates the
problem:
using (var context = new NorthwindEntities())
{
var order = CreateOrder();
order.OrderStatus = (byte)OrderStatus.Fulfilled;
context.Orders.AddObject(order);
context.SaveChanges();
order.OrderStatus = (byte)OrderStatus.Paid;
context.SaveChanges();
}
The current implementation of the validation logic in the
Order
class has no knowledge of
the previous state of the entity and cannot distinguish a valid order, for which a payment
had just been processed, from a rogue order that was tampered with.
Accessing Original Property Values with ObjectStateManager
As discussed in Chapter 2, the Entity Framework keeps track of all changes made to enti-
ties in order to support optimistic concurrency. Each
ObjectContext
, such as the
NorthwindEntities
in these examples, has an
ObjectStateManager
, which uses
ObjectStateEntry
objects to keep track of both
current
and
original
property values for
each entity. Here is how you can take advantage of this capability and compare the
current value of the
OrderStatus
property with the original: