Reputation: 164
I am trying to override the SaveChanges()
method in my DbContext
class, this because I try to get the name of the entity with a row added, deleted or updated an the respective ID of the row and the action performed.
I don't know how to do this.
This is with logs actions purposes.
Greetings in advance.
Upvotes: 2
Views: 2636
Reputation: 6766
You need to override SaveChanges method of DbContext and use ChangeTracker to track the changes made to entities before it gets saved to database.public
public class ChangeLog
{
public string EntityName { get; set; }
public string PropertyName { get; set; }
public string OldValue { get; set; }
public string NewValue { get; set; }
}
public override int SaveChanges()
{
var modifiedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified).ToList();
foreach (var change in modifiedEntities)
{
var entityName = change.Entity.GetType().Name;
foreach(var prop in change.OriginalValues.PropertyNames)
{
var originalValue = change.OriginalValues[prop].ToString();
var currentValue = change.CurrentValues[prop].ToString();
if (originalValue != currentValue)
{
ChangeLog log = new ChangeLog()
{
EntityName = entityName,
PropertyName = prop,
OldValue = originalValue,
NewValue = currentValue,
};
ChangeLogs.Add(log);
}
}
}
return base.SaveChanges();
}
In above snippet we have queried change tracker api to fetch the entities that are modified
var modifiedEntities = ChangeTracker.Entries()
.Where(p => p.State == EntityState.Modified).ToList();
Same way you can query entities that are added and deleted.
Edit
object GetPrimaryKeyValue(DbEntityEntry entry)
{
var stateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
return stateEntry.EntityKey.EntityKeyValues[0].Value;
}
Note: If you have Identity Insert set to On then for added entity above snippet will not work.
Upvotes: 4