DbContext SaveChanges () - Detecting Updated Objects

I overridden the SaveChanges () method in the Entity Framework 4.1 DbContext class.

My redefinition is as follows:

public override int SaveChanges() { IEnumerable<DbEntityEntry> modifiedEntityEntries = ChangeTracker.Entries().Where( e => e.State == EntityState.Modified ); Debug.Assert( modifiedEntityEntries.Count() == 2 ); int savedChanges = base.SaveChanges(); Debug.Assert( savedChanges == 1 ); // HELP! At this point, how do I tell Which of the two "Modified" entities actually updated a row in the database? return savedChanges; } 

Suppose there are 2 objects in the context, and both of them are marked as Modified (EntityState.Modified). One of them has been modified and differs from the database row. The other is no different from the base row of the database; it is simply marked as such.

How can I tell by calling SaveChanges () which of the two entities actually updated the row in the database and which of them was not really changed?

+6
source share
1 answer

So we do it in our code. Lazy loading and proxy creation is available.

Please note that when creating a proxy server, EF will know which property has changed, you do not need to go to the database. The only place EF does not know is if any other context changed the row (concurrency error) to avoid using the RowVersion column / property

In the constructor:

  public DataContext() : base() { this.Configuration.ProxyCreationEnabled = true; this.Configuration.LazyLoadingEnabled = true; var objectContext = ((IObjectContextAdapter)this).ObjectContext; objectContext.SavingChanges += new EventHandler(objectContext_SavingChanges); } private void objectContext_SavingChanges(object sender, EventArgs e) { var objectContext = (ObjectContext)sender; var modifiedEntities = objectContext.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added | System.Data.EntityState.Modified); foreach (var entry in modifiedEntities) { var entity = entry.Entity as BusinessBase; if (entity != null) { entity.ModDateTime = DateTime.Now; entity.ModUser = Thread.CurrentPrincipal.Identity.Name; } } } 
+3
source

Source: https://habr.com/ru/post/901464/


All Articles