简体   繁体   中英

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

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

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM