Entity Framework Entity Entity

I want to check every object when saving. That is, I have some C # user-defined function in every entity class that validates the data.

How can i do this? I do not want to use database restrictions because they cannot express my limitations.

Should I implement some kind of interface ???

+3
source share
2 answers

Entity framework 3.5 and 4.0 offers even called SavingChanges. Entity framework 4.0 and 4.1 has a SaveChangesvirtual method (as already mentioned).

You can either override the method, or use an 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 the DbContext API (EF 4.1) you should 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();
}

, , Validate.

+4

ObjectContext.SaveChanges EF 4.0. .

http://msdn.microsoft.com/en-us/library/dd395500.aspx

( :)) . ObjectStateManager .

, ,

http://www.testmaster.ch/EntityFramework.test

+4

All Articles