Databases Reference
In-Depth Information
using (var context = new NorthwindEntities())
{
var order = CreateOrder();
order.OrderStatus = (byte)OrderStatus.Fulfilled;
context.Orders.AddObject(order);
context.SaveChanges();
order.OrderStatus = (byte)OrderStatus.Paid;
var stateEntry = context.ObjectStateManager.GetObjectStateEntry(order);
byte originalStatus = (byte)stateEntry.OriginalValues[“OrderStatus”];
if (originalStatus == (byte)OrderStatus.Fulfilled &&
order.OrderStatus != (byte)OrderStatus.Fulfilled)
{
// We have a problem
}
context.SaveChanges();
}
In this new version, the code first calls the
GetObjectStateEntry
method of the
ObjectStateManager
to retrieve an
ObjectStateEntry
, which allows accessing original
property values of the entity via its
OriginalValues
property. This property returns an
object of type
DbDataRecord
defined in the
System.Data
namespace by the ADO.NET
framework. You can use its indexer to access the original property values by name. Having
retrieved the original value of the OrderStatus property, you can compare it against the
current value in the entity object itself.
Accessing Original Property Values in Validation Methods
Out of the box, validation methods, whether they are defined by applying the
CustomValidationAttribute
or implementing the
IValidatableObject
interface, do
not have access to the
ObjectStateEntry
, the
ObjectStateManager
, or even the
ObjectContext
for that matter. To access the original property values inside the validation
methods, this information needs to be supplied to them by the
Validate
method of the
UnleashedObjectContext
class. Luckily,
ValidationContext
(which all validation methods
can receive as a parameter) defines the
Items
property of type
IDictionary<object,
object>
specifically
for that purpose.
Here is how the
Validate
method in the
UnleashedObjectContext
was modified to create
the
Items
dictionary and place an
ObjectStateEntry
instance in it for the validation
methods to find:
private void Validate(ObjectStateEntry stateEntry)
{
object entity = stateEntry.Entity;
var items = new Dictionary<object, object>();
items[typeof(ObjectStateEntry)] = stateEntry;