I want to validate each entity when saving. That is, I have some custom C# function in each entity class that validates the data.
How can I do that? I don't want to use database constraints because they cannot express my constraints.
Should I implement some interface???
Entity framework 3.5 and 4.0 offers even called SavingChanges. Entity framework 4.0 and 4.1 has SaveChanges method virtual (as already mentioned).
You can either override method or use event handler and write code like this for 3.5 and 4.0:
var entities = context.ObjectStateManager
.GetObjectStateEntries(EntitiState.Modified | EntityState.Added)
.Where(e => !e.IsRelationship)
.Select(e => e.Entity)
.OfType<YourEntityType>();
foreach(var entity in entities)
{
entity.Validate();
}
In DbContext API (EF 4.1) you must use
var entities = context.ChangeTracker
.Entries<YourEntityType>()
.Where(e.State == EntityState.Added || e.State == EntityState.Modified)
.Select(e => e.Entity);
foreach(var entity in entities)
{
entity.Validate();
}
You can use custom interface implemented by your entities which will expose Validate method.
The ObjectContext.SaveChanges method is virtual since EF 4.0. Overwrite this method and validate all entities there.
http://msdn.microsoft.com/en-us/library/dd395500.aspx
Iterate over all entities (not the deleted ones :)) in the context. Use the ObjectStateManager to gain access to the entities in the context.
Hope this helps and best regards,
http://www.testmaster.ch/EntityFramework.test
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With