2

我花了一些時間閱讀了一些關於審計追蹤的文章和文章,但仍然無法弄清楚。首先用EF 4.2代碼攔截並記錄更改

我需要的是一個非常基本的審計系統,這將使我的結果,如:

  • 客戶「張三」是由
  • 客戶「李四」被創造「用戶」「刪除其他用戶李四」
  • 從地址‘用戶’被修改‘’
  • 客戶‘其它用戶‘

我’被刪除’李四試圖覆蓋上的DbContext調用SaveChanges事件,但我被困具有以下問題:

public override int SaveChanges() 
{ 

     foreach (DbEntityEntry<IAuditable> entry in ChangeTracker.Entries<IAuditable>()) 
     { 
      if (entry.State == EntityState.Added) 
      { 
       // since the object was not added yet, if I write to log in here and 
       // for some reason SaveChanges fail, I will end up with a fake log entry 
      } 
      else if (entry.State == EntityState.Modified) 
      { 
       // same in here 
      } 
     } 

     return base.SaveChanges(); 

     // here the state for all entries have changed to Unchanged or Detached. 
     // detached is probably the one that was deleted however the 「Unchanged」 
     // could be new or modified records. 
} 

我知道我可以使用數據庫觸發器上做到這一點,但我想保持它在這裏讓我有更多的控制在它之上,因爲我不是一個SQL人,部署應用程序後,我不會有太多的控制數據庫。

我很確定我在這裏錯過了很簡單的東西。 我感謝任何幫助。

在此先感謝。

回答

2

您可以隨時檢查上下文中是否有任何審覈條目,並在調用SaveChanges時將其刪除。它將解決您的第一個問題 - 您將始終刪除先前的審覈條目,然後再創建新的審覈條目。

第二個問題無法用DbContext API解決。 DbContext API是ObjectContext API的簡化,這種簡化消除了複雜場景所需的方法。一種這樣的方法是SaveChanges的超負荷版本,能夠不接受改變(不改變實體的狀態)。

您可以通過IObjectContextAdapterDbContext轉換爲ObjectContext。即使有ObjectContext它也不會直截了當:

// If you want to have audits in transaction with records you must handle 
// transactions manually 
using (TransactionScope scope = new TransactionScope(...)) 
{ 
    ObjectContext context = ((IObjectContextAdapter)this).ObjectContext; 
    context.SaveChanges(SaveOptions.DetectChangesBeforeSave); 

    var audits = new List<Audit>(); 

    // Now you must call your audit code but instead of adding audits to context 
    // you must add them to list. 

    // This is the reason why you must not add changes to context. You must accept 
    // old changes prior to adding your new audit records otherwise EF will perform 
    // changes again. If you add your entities to context and call accept before 
    // saving them your changes will be lost 
    context.AcceptAllChanges(); 

    // Now add all audits from list to context 

    context.SaveChanges(); 

    // Complete the transaction 
    scope.Complete(); 
} 
+0

性能怎麼樣?在將DbContext轉換爲ObjectContext後保存數據不是較慢? – Saber

+0

@Saber:DbContext內部使用ObjectContext,所以不應該有任何性能影響。 –