C # validation overrides the SaveChanges () method. How to find out the foreign keys of an object and its value from a table

I override the SaveChange () method. I want to log all changes made by an entity to the database in plain text, for example, "abc updated Name john to doe, ..." etc. I got the functionality, but when there is a foreign key in the entity that will be updated, like country_Id, which points to the Country table, it generates text, for example "abc updated Country_Id 1 to 3, ..." that I do not want it be like "abc updated Country Canada to Australia, ..."

To achieve this, he must know the foreign keys and their meaning

My code is:

public override int SaveChanges() { List<string> listChanges = new List<string>(); List<string> listTable = new List<string>(); var objectStateManager = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager; IEnumerable<ObjectStateEntry> changes = objectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added | EntityState.Deleted); foreach (ObjectStateEntry stateEntryEntity in changes) { var modifiedProperties = stateEntryEntity.GetModifiedProperties(); foreach (var propName in modifiedProperties) { if (Convert.ToString(stateEntryEntity.OriginalValues[propName]) != Convert.ToString(stateEntryEntity.CurrentValues[propName])) { listTable.Add(stateEntryEntity.EntityKey.EntitySetName); listChanges.Add(propName + " From " + Convert.ToString(stateEntryEntity.OriginalValues[propName]) + " to " + Convert.ToString(stateEntryEntity.CurrentValues[propName])); } //System.Console.WriteLine("Property {0} changed from {1} to {2}", // propName, // stateEntryEntity.OriginalValues[propName], // stateEntryEntity.CurrentValues[propName]); } } return base.SaveChanges(); } 
+5
source share
1 answer

There is a function to achieve this, I used changetracker to change the track and log.You gets all the changes right before distributing your context, so shortly you can build like this:

 public override int SaveChanges() { foreach (var history in ChangeTracker.Entries() .Where(e => e.Entity is IModificationHistory && (e.State == EntityState.Added || e.State == EntityState.Modified)) .Select(e => e.Entity as IModificationHistory) ) { history.DateModified = DateTime.Now; if (history.DateCreated == DateTime.MinValue) history.DateCreated = DateTime.Now; } var result = base.SaveChanges(); foreach (var history in ChangeTracker.Entries() .Where(e => e.Entity is IModificationHistory) .Select(e => e.Entity as IModificationHistory) ) history.IsDirty = false; return result; } 

You can also specify your entry directly in front of base.savechanges ()

This is my story interface

  public interface IModificationHistory { DateTime DateModified { get; set; } DateTime DateCreated { get; set; } bool IsDirty { get; set; } } 
0
source

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


All Articles