EntityFramework Change Tracking不跟踪更改
本文关键字:跟踪 Change Tracking EntityFramework | 更新日期: 2023-09-27 18:14:19
我正在使用实体框架7,我需要能够跟踪变化。我最终在SaveChanges上做了这样的事情,然后在最后使用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;
}
}
最终调用获取表更改记录:
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()
});
}
}
}
}
现在我面临的问题是OriginalValue &CurrentValue和输入的新值。它没有跟踪原始值是什么。
我有:
this.ChangeTracker.AutoDetectChangesEnabled = true;
然而,我仍然没有得到它为我提供正确的原始值和当前值。如有任何帮助,不胜感激。
所以我找到了我自己的问题…我面临的问题是我正在附加需要更新的记录。我最终通过创建更新函数来更新记录:
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;
}