Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework entity integrity

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???

like image 236
Cartesius00 Avatar asked Sep 10 '26 18:09

Cartesius00


2 Answers

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.

like image 63
Ladislav Mrnka Avatar answered Sep 13 '26 08:09

Ladislav Mrnka


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

like image 27
yonexbat Avatar answered Sep 13 '26 08:09

yonexbat