EntityFramework DBContext Audit中的错误

时间:2013-02-04 04:40:42

标签: c# entity-framework-5

我的目标是保存,同时创建审核日志。当实体进入状态改变后运行应用程序var result = base.SaveChnages()时,如何克服这个问题可以任何一个帮助appriciate

     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;
        }
    }

1 个答案:

答案 0 :(得分:0)

重写'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);
        }      
     }  
}