我知道那里有几个类似的帖子,但我找不到任何解决此问题的方法。
我想在 Entity Framework 6 中添加、更改或删除实体(软删除)时添加(某种)AudioLog。我已经覆盖了 SaveChanges,因为我只想为添加、修改或删除的 EntityStates 添加日志条目,我在第一次调用 SaveChanges 之前获取了列表。问题是,因为我需要记录已执行的操作,所以我需要检查实体的 EntityState。但是在调用 SaveChanges 之后,所有条目的 EntityState 都未更改。
public override int SaveChanges()
{
using (var scope = new TransactionScope())
{
var modifiedEntries = ChangeTracker.Entries()
.Where(e => e.State == EntityState.Added || e.State == EntityState.Deleted || e.State == EntityState.Modified)
.ToList();
int changes = base.SaveChanges();
foreach (var entry in modifiedEntries)
{
ApplyAuditLog(entry);
}
base.SaveChanges();
scope.Complete();
return changes;
}
}
private void ApplyAuditLog(DbEntityEntry entry)
{
ILog entity = entry.Entity as ILog;
if (entity != null)
{
LogOperation operation;
switch (entry.State)
{
case EntityState.Added:
operation = LogOperation.CreateEntity;
break;
case EntityState.Deleted:
operation = LogOperation.DeleteEntity;
break;
case EntityState.Modified:
operation = LogOperation.UpdateEntity;
break;
default:
throw new ArgumentOutOfRangeException();
}
AuditLog log = new AuditLog
{
Created = DateTime.Now,
Entity = entry.Entity.GetType().Name,
EntityId = entity.Id,
Operation = operation,
};
AuditLog.Add(log);
}
}