2010-07-01 54 views
0

我有一個模擬後端MSSQL數據庫的EDM(phoneDB)。我開發了一個ASP.NET(VB)應用程序,允許用戶編輯此數據庫中的信息。當有人編輯記錄條目時,我想記錄此操作。實體框架:創建更改歷史記錄

現在,我做了以下內容:

對於Each..Next,檢查條目是否是有其entitystate修改的對象。

並且如果不是。結束如果確保我們不處理關係實體或空實體。

現在這是它變得模糊的地方。我想要做的是從這些修改後的對象中獲取信息並將其記錄到數據庫中。現在,我有這樣的事情:

Dim audit as History 
audit.action = "Changed information in " & propName & " to " & entry.CurrentValues(propName) & " from " & entry.OriginalValues(propName) 
audit.action_by = this_user 
audit.action_date = Date.Now 
audit.extension_id = 

我不知道,但是,如何分辨它從進入拉一個特定的屬性。例如,我需要獲得(僞代碼)是這樣的:

audit.extension_id = entry.OriginalValues(extension_id) 

回答

0

下面是我最終完成它:

Private Shared Sub context_SavingChanges(ByVal sender As Object, ByVal e As EventArgs) 
     ' This allows us to record a history of the changes made by the user to the database. The record is created automatically by EF, but we need to save it to the database 
     ' for permanent retention. 
     For Each entry As ObjectStateEntry In DirectCast(sender, ObjectContext).ObjectStateManager.GetObjectStateEntries(EntityState.Modified) 
      If Not entry.IsRelationship And entry.Entity IsNot Nothing Then 
       For Each propName As String In entry.GetModifiedProperties() 
        Dim context As New AppsEntities() 
        Dim audit As New History 
        audit.action_note = "Changed information in " & propName & " to " & entry.CurrentValues(propName) & " from " & entry.OriginalValues(propName) 
        audit.action_by = CStr(HttpContext.Current.Session("person_name")) 
        audit.action_date = Date.Now 
        audit.extension_id = entry.CurrentValues.GetValue(0) 
        context.AddToHistories(audit) 
        context.SaveChanges() 
       Next 

      End If 

     Next 
    End Sub 
1

我不明白什麼叫「從一個入口拉特定財產」是什麼意思?您編寫的(僞)代碼沒有太多說明,您的情況是什麼extesion_id?如果extension_id是一個實體的屬性名稱,那麼通過調用entry.OriginalValues(「extension_id」)來獲得它的原始值,但我確信你知道這一點。

順便說一句,你可以使用沒有數據層的觸發器甚至知道它的數據庫本身做複雜的歷史記錄。這是一個相當老把戲和工作速度快,見this