Databases Reference
In-Depth Information
Instead, change the ObjectContext class in your project so that it notifies the entity
objects before they are saved and allows the entity objects to execute property interaction
rules before the validation is performed. For example, the
Unleashed.EntityFramework
assembly in the sample solution accompanying this topic defines an interface called
ISavableObject
(for consistency with the built-in
IValidatableObject
interface), that
entity classes can implement when they require property interaction logic.
interface ISavableObject
{
void BeforeSave(ObjectStateEntry stateEntry);
}
In the
Order
entity class, you can now implement this interface and have the
BeforeSave
method get the original value of the
OrderStatus
property from the
ObjectStateEntry
,
compare it to the current value in the
OrderStatus
property itself, and set the
SubmittedDate
property with the system date and time.
partial class Order : ISavableObject
{
public void BeforeSave(ObjectStateEntry stateEntry)
{
byte? oldStatus = (byte)DataModel.OrderStatus.Draft;
if (stateEntry.State == EntityState.Modified)
oldStatus = stateEntry.OriginalValues.Get(() => this.OrderStatus);
if (this.OrderStatus == (byte)DataModel.OrderStatus.Submitted &&
oldStatus == (byte)DataModel.OrderStatus.Draft)
{
this.SubmittedDate = DateTime.Now;
}
}
}
The
UnleashedObjectContext
class calls the
BeforeSave
method of each entity object that
implements the
ISavableObject
interface.
partial class UnleashedObjectContext
{
private void BeforeSaveChanges(ObjectStateEntry stateEntry)
{
var savable = stateEntry.Entity as ISavableObject;
if (savable != null)
savable.BeforeSave(stateEntry);
if (stateEntry.State != EntityState.Deleted)
this.Validate(stateEntry);
}
}