Entity Framework SaveChanges two behaviors depending on how I add to the DbContext

I overridden my db.SaveChanges (), so I can call my FluentValidation validation checks before it actually tries to save it.

I have a validator for each object marked with the IValidatableEntity identifier, and if the entity matches it, it will call it and pass the objectStateEntry object.

public virtual IEnumerable<string> SaveChanges(User user)
{
     List<string> validationErrors = new List<string>();
     if (this.Configuration.ValidateOnSaveEnabled)
     {
         foreach (var entry in ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager
              .GetObjectStateEntries(System.Data.Entity.EntityState.Added | System.Data.Entity.EntityState.Deleted | System.Data.Entity.EntityState.Modified | System.Data.Entity.EntityState.Unchanged)
              .Where(entry => (entry.Entity is IValidatableEntity)))
              {
                  validationErrors.AddRange(((IValidatableEntity)entry.Entity).Validate(entry));
              }
         }

    if (!validationErrors.Any())
    { .....

The problem is that I get two different behaviors depending on how I add the object to dbContext. I assume that he only notes that the aggregate root changes and only gives him a record?

// Example A - Calls the Organisation Validator Only
 organisation.Client.Add(client); 

// Example B - Calls the Client Validator - which is correct
db.Client.Add(client);

, EF , (/) ? , , EF- , .

Fluent Validations, ? , . ( db ..).

+3
2

DetectChanges SaveChanges ( , GetObjectStateEntries):

this.ChangeTracker.DetectChanges();

Client , organisation.Client.Add(client) EF- ( POCO), db.Client.Add(client) , DbSet<T>.Add , .

, - EF SaveChanges, base.SaveChanges , , . base.SaveChanges SaveChanges, GetObjectStateEntries. Client Detached (.. ) Added. , DetectChanges , GetObjectStateEntries.

+2

, organisation POCO, :

organisation.Client.Add(client);

POCO ICollection POCOs. EF , .

, :

db.Client.Add(client);

POCO ICollection (DbCollectionEntry), Entity Framework , ( ). -, (. fooobar.com/questions/349949/...).

, (. @Slauma). - - organisation POCO. , :

var newOrganisation = dbContext.Set<Organisation>().Create();

, , organisation.

+1

All Articles