我正在使用实体框架6,我正在使用EntityFramework Extended来执行一些批量更新和批量删除。批量更新和批量删除工作OK,但我还需要知道被更新/删除的实体(即当前和以前的值)。我认为使用EntityFramework提供的AuditLogger。扩展将为我提供的实体的细节,其中更新或删除,但这似乎并非如此。例如,使用下面的代码,即
var auditor =dbContext.BeginAudit();
dbContext.Addresses.Update(ent => new Address { AddressId = 1190 });
dbContext.SaveChanges();
var changes = auditor.LastLog;
这是一个简单的批量更新,将所有addressid更新为1190
。如果我检查changes.Entities
,它返回一个0的Count,即一个空列表。
我所期望的是changes.Entities
将包含所有具有旧值的"旧"实体,然后addressId更改为1190
。
是我错了还是这确实是正确的行为?使用实体框架扩展批处理更新/删除时,如何获得所有更新实体的审计日志
谢谢
您应该启用Auditor
var auditConfiguration = AuditConfiguration.Default;
auditConfiguration.IncludeRelationships = true;
auditConfiguration.LoadRelationships = true;
auditConfiguration.DefaultAuditable = true;
添加到你的应用程序初始化的地方,例如Global.asax.cs
据我所知,你不能使用EF.Extended获得旧值。下面是我的解决方案:
重写上下文中的SaveChanges方法
public override int SaveChanges()
{
return SaveChanges(false);
}
public int SaveChanges(bool disableAudit)
{
var result = -1;
try
{
if (!disableAudit)
{
foreach (var entity in ChangeTracker.Entries().Where(x => x.State == EntityState.Added ||
x.State == EntityState.Modified ||
x.State == EntityState.Deleted))
{
ProccessAuditLog(entity);
}
}
}
catch (Exception ex)
{
// handle the ex here
}
finally
{
//save changes
result = base.SaveChanges();
}
return result;
}
并在过程审核日志中添加方法:
private void ProccessAuditLog(DbEntityEntry entry)
{
var entity = entry.Entity;
var entityType = GetEntityType(entity.GetType());
var oldValue = Activator.CreateInstance(entityType); ;
if (entry.State == EntityState.Modified)
{
// entry.OriginalValues doesn't load navigation properties for changed entity so we should reload the object from db to get it
// save current values
var newValue = Activator.CreateInstance(entityType);
Mapper.DynamicMap(entity, newValue, entity.GetType(), entityType);
// reload old values for entity from the db
entry.Reload();
Mapper.DynamicMap(entry.Entity, oldValue, entity.GetType(), entityType);
// revert reloading changes in entity
entry.CurrentValues.SetValues(newValue);
entry.OriginalValues.SetValues(oldValue);
entry.State = EntityState.Modified;
entity = newValue;
}
if (entry.State == EntityState.Deleted)
{
// reload old values for entity from the db
entry.Reload();
Mapper.DynamicMap(entry.Entity, oldValue, entity.GetType(), entityType);
// revert reloading changes in entity
entry.OriginalValues.SetValues(oldValue);
entry.State = EntityState.Deleted;
entity = null;
}
// here is you can proccess old entity in 'oldValue' and new entity in 'entity'
// then save your log to db using SaveChanges(true) to prevent StackOverFlow exception
}
作为Mapper
,你可以使用AutoMapper
方法获取基实体类型而不是代理类型:
private Type GetEntityType(Type entityType)
{
return entityType.BaseType != null && entityType.Namespace == "System.Data.Entity.DynamicProxies"
? entityType.BaseType
: entityType;
}
希望对你有帮助