Reputation: 805
I am using Entity Framework 7 and I need to be able to track changes. I am ultimately doing something like this during the on SaveChanges I am overriding it then at the end using base.SaveChanges():
foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified).ToList())
{
// For each changed record, get the audit record entries and add them
foreach (TableChange x in GetTableChangeRecordsForChange(ent, _ChangeUser))
{
this.TableChanges.Add(x);
val = true;
}
}
This ultimately calls out to get table change records:
private IEnumerable<TableChange> GetTableChangeRecordsForChange(EntityEntry dbEntry, string userId)
{
List<TableChange> result = new List<TableChange>();
foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State == EntityState.Deleted || p.State == EntityState.Modified).ToList())
{
// For each changed record, get the audit record entries and add them
foreach (TableChange x in GetTableChangeRecordsForChange(ent, _ChangeUser))
{
this.TableChanges.Add(x);
val = true;
}
}
if (dbEntry.State == EntityState.Modified)
{
foreach (var property in dbEntry.Entity.GetType().GetTypeInfo().DeclaredProperties)
{
// For updates, we only want to capture the columns that actually changed
if (!object.Equals(dbEntry.Property(property.Name).OriginalValue, dbEntry.Property(property.Name).CurrentValue))
{
result.Add(new TableChange()
{
Action = "U",
ColumnName = property.Name,
CreatedBy = userId,
CreatedOn = DateTime.Now,
OldValue = dbEntry.Property(property.Name).OriginalValue.ToString(),
NewValue = dbEntry.Property(property.Name).CurrentValue.ToString(),
TableName = dbEntry.Entity.GetType().GetTypeInfo().Name,
TableID = dbEntry.Property("ID").CurrentValue.ToString()
});
}
}
}
}
Now the issue that I am facing is both OriginalValue & CurrentValue and the new value that was entered. It is not tracking what the original value was.
I do have:
this.ChangeTracker.AutoDetectChangesEnabled = true;
Yet I am still not getting it to provide me the original and current value correctly. Any help is greatly appreciated.
Upvotes: 0
Views: 3642
Reputation: 805
So I figured out my own issue... the issue I was facing was I was attaching the record that needed updating. I ultimately updated the record by creating my Update Function:
public T ADMSUpdate<T>(T entity, T originalEntity)
{
object propertyValue = null;
PropertyInfo[] properties = originalEntity.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
propertyValue = null;
if (null != property.GetSetMethod())
{
PropertyInfo entityProperty = entity.GetType().GetProperty(property.Name);
propertyValue = entity.GetType().GetProperty(property.Name).GetValue(entity, null);
if (null != propertyValue)
{
property.SetValue(originalEntity, propertyValue, null);
}
}
}
return entity;
}
Upvotes: 1