Databases Reference
In-Depth Information
namespace Unleashed.EntityFramework
{
public class UnleashedObjectContext : ObjectContext
{
private const EntityState ChangedEntityStates =
EntityState.Added | EntityState.Modified | EntityState.Deleted;
public override int SaveChanges (SaveOptions options)
{
IEnumerable<ObjectStateEntry> stateEntries = this. ObjectStateManager
.GetObjectStateEntries(ChangedEntityStates)
.Where(stateEntry => !stateEntry.IsRelationship);
foreach (ObjectStateEntry stateEntry in stateEntries)
this.BeforeSaveChanges(stateEntry);
return base.SaveChanges(options);
}
private void BeforeSaveChanges (ObjectStateEntry stateEntry)
{
if (stateEntry.State != EntityState.Deleted)
this.Validate(stateEntry);
}
private void Validate (ObjectStateEntry stateEntry)
{
object entity = stateEntry.Entity;
var context = new ValidationContext(entity, null, null);
Validator. ValidateObject (entity, context, true);
}
}
}
First, the overridden SaveChanges method gets a list of state entries for all changed
entities from the ObjectStateManager that keeps track of all entities in the ObjectContext .
For each of the changed state entries, it calls the BeforeSaveChanges method responsible
for performing all entity-specific actions that need to occur before the changes are saved
to the database. As we continue expanding Entity Framework capabilities to solve real-
world business problems, this method will grow. At this point, however, it is only respon-
sible for validation of the changed entities. The Validate method extracts the actual
entity from an ObjectStateEntry and calls the familiar ValidateObject method of the
Validator class. If the entity object is invalid, the ValidateObject method throws a
 
Search WWH ::




Custom Search