我正在使用 EF 4.3.1,我已经覆盖了上下文中的 SaveChanges(),以便我可以获得对象及其状态的列表并在我的审计日志表中创建条目。我需要将记录的 id 存储在审计日志表中,以便对其进行引用。这是插入记录时出现的问题,因为在保存之前我无法访问 id。有什么方法可以在那时获得 id 吗?
public override int SaveChanges()
{
ChangeTracker.DetectChanges();
var objectStateManager = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager;
var modifiedAuditableEntities = objectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added).Where(e => (IAuditable)e.Entity != null);
foreach (var entry in modifiedAuditableEntities)
{
var entity = (IAuditable)entry.Entity;
if (entity != null)
{
switch (entry.State)
{
case EntityState.Added:
entity.IsAdded = true;
break;
case EntityState.Deleted:
entity.IsDeleted = true;
break;
case EntityState.Modified:
entity.IsModified = true;
break;
}
this.EntitySet<AuditLogEntry>().Add(this.auditLogService.CreateAuditLogEntryForEntity((IAuditable)entry.Entity));
}
return base.SaveChanges();
}