代码之家  ›  专栏  ›  技术社区  ›  Dave Mackey chem1st

实体框架:创建更改历史

  •  0
  • Dave Mackey chem1st  · 技术社区  · 16 年前

    我有一个EDM(phoneDB)为后端MSSQL数据库建模。我已经开发了一个ASP.NET(VB)应用程序,它允许编辑这个数据库中的信息。当有人编辑记录条目时,我想记录此操作。

    For 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)
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Boris B.    16 年前

    顺便说一句,您可以使用触发器在数据库中进行复杂的历史记录,而数据层甚至不知道它。这是一个相当古老的把戏,效果很快,明白吗 this

        2
  •  0
  •   Dave Mackey chem1st    16 年前

      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