我知道那里有几个类似的帖子,但我找不到任何解决这个问题的方法。
我想在实体框架 6 中添加、更改或删除实体(软删除)时添加(某种)音频日志。我已经覆盖了保存更改,因为我只想为添加、修改或删除的实体状态添加日志条目,所以我在第一次调用保存更改之前获取列表。问题是,因为我需要记录已执行的操作,所以我需要检查实体的实体状态。但在调用 SaveChanges 后,所有条目的实体状态都保持不变。
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);
}
}
啊...不对!!对于新添加的实体来说,id 只会是一个"问题",因此通过将列表一分为二(一个用于修改/删除,一个用于添加),我分两个阶段创建 AuditLog。
对于想要应用这种AuditLog的其他任何人,这是我的工作代码:
public override int SaveChanges()
{
using (var scope = new TransactionScope())
{
var addedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added).ToList();
var modifiedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Deleted || e.State == EntityState.Modified).ToList();
foreach (var entry in modifiedEntries)
{
ApplyAuditLog(entry);
}
int changes = base.SaveChanges();
foreach (var entry in addedEntries)
{
ApplyAuditLog(entry, LogOperation.CreateEntity);
}
base.SaveChanges();
scope.Complete();
return changes;
}
}
private void ApplyAuditLog(DbEntityEntry entry)
{
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();
}
ApplyAuditLog(entry, operation);
}
private void ApplyAuditLog(DbEntityEntry entry, LogOperation logOperation)
{
ILog entity = entry.Entity as ILog;
if (entity != null)
{
AuditLog log = new AuditLog
{
Created = DateTime.Now,
Entity = entry.Entity.GetType().Name,
EntityId = entity.Id,
Operation = logOperation,
};
AuditLog.Add(log);
}
}
您可以将 EntityState 保存到 Entity 键值对,并在第一次更改后使用它。
VaR 条目 = 这个。ChangeTracker.Entries().其中(e => e.State == EntityState.add || e.State == EntityState.Modified || e.State == EntityState.Deleted).Select(e => new { e.State, e }).ToList();