2013-02-04 53 views
0

我的目標是保存和審計日誌同時創建。運行該應用程序變種結果時= base.SaveChnages()後,實體進入狀態改變,如何任何一個可以幫助並欣賞EntityFramework DBContext審計錯誤

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

回答

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