Reputation: 24384
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???
Upvotes: 3
Views: 467
Reputation: 364319
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.
Upvotes: 4
Reputation: 3012
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
Upvotes: 4