如何从Entity Framework的Auditlog中获取实体的ID 6
我知道这里有几个类似的帖子,但我找不到解决此问题的任何解决方案。
我想在实体框架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);
}
}
呃...当然! 这个id对于新添加的实体来说只是一个“问题”,所以通过将列表分成两个(一个用于修改/删除,另一个用于添加),我创建两个阶段的审计日志。
对于任何想要应用这种审计日志的人,这里是我的工作代码:
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);
}
}
链接地址: http://www.djcxy.com/p/33547.html
上一篇: How to get id from entity for Auditlog in Entity Framework 6