【问题标题】:Entity Framework: Create Change History实体框架:创建更改历史
【发布时间】:2010-07-01 13:13:40
【问题描述】:

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

现在,我正在做以下事情:

For Each..Next 检查条目是否是已修改其实体状态的对象。

And If Not..End If 这样可以确保我们不处理关系实体或空实体。

现在这是变得模糊的地方。我想要做的是从这些修改过的对象中获取信息并将它们记录到数据库中。现在我有这样的东西:

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)

【问题讨论】:

    标签: asp.net entity-framework ado.net entity-framework-4


    【解决方案1】:

    我不明白“从条目中提取特定属性”是什么意思?您编写的(伪)代码并没有说明太多,在您的情况下 extesion_id 是什么?如果 extension_id 是实体的属性名称,那么您可以通过调用 entry.OriginalValues("extension_id") 来获取它的原始值,但我很确定您知道这一点。

    顺便说一句,您可以使用触发器在数据库本身中进行复杂的历史记录,而数据层甚至都不知道它。这是一个相当古老的技巧,而且效果很快,请参阅this

    【讨论】:

      【解决方案2】:

      我最后是这样完成的:

        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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-30
        • 2014-08-23
        • 1970-01-01
        • 2018-09-22
        • 1970-01-01
        • 2010-11-30
        • 2012-07-16
        • 1970-01-01
        相关资源
        最近更新 更多