EntityFramework DBContext audit中的错误

本文关键字:错误 audit DBContext EntityFramework | 更新日期: 2023-09-27 17:57:14

我的目标是同时保存和创建审核日志。 运行时应用程序变量结果 =base。保存Chnages()在实体条目状态改变后,如何克服这个问题,任何人都可以帮助申请

     public override int SaveChanges()
    {
        ChangeTracker.DetectChanges();
        using (var scope = new TransactionScope())
        {
            var objectStateManager = ((IObjectContextAdapter) this).ObjectContext.ObjectStateManager;
            var modifiedAuditableEntities =
                objectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added).Where(
                    e => (IAuditable) e.Entity != null);
            var result = base.SaveChanges();
            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));
                }
            }
            base.SaveChanges();
            scope.Complete();
            return result;
        }
    }

EntityFramework DBContext audit中的错误

重写 'OnContextCreated' 方法并绑定 'SaveChanges' 事件处理程序,如下所示:

public partial class MyDataModel
{
    partial void OnContextCreated()
    {
        this.SavingChanges += new EventHandler(CreateAuditLog);
    }
    void CreateAuditLog(object sender, EventArgs e)
    {
         var changes = this.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted | EntityState.Modified);
        if (!changes.Any())
            return;
        var auditDataList = new List<AuditLogEntry>();
        foreach (ObjectStateEntry stateEntryEntity in changes)
        {
            if (!stateEntryEntity.IsRelationship && stateEntryEntity.Entity != null && !(stateEntryEntity.Entity is AuditLogEntry))
            {
                var audit = new AuditLogEntry();
                auditDataList.Add(audit);
            }
        }
        if (auditDataList.Count > 0)
        {
            foreach (var audit in auditDataList)
                this.AddToAuditLogEntries(audit);
        }      
     }  
}