实体框架:保存对象?

时间:2010-07-01 14:58:02

标签: entity-framework ado.net entity-framework-4 ado.net-entity-data-model

这是我的代码:

Partial Public Class AppsEntities
Private Sub OnContextCreated()
    AddHandler Me.SavingChanges, AddressOf context_SavingChanges
End Sub
Private Shared Sub context_SavingChanges(ByVal sender As Object, ByVal e As EventArgs)
    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 audit As New History
                audit.action = "Changed information in " & propName & " to " & entry.CurrentValues(propName) & " from " & entry.OriginalValues(propName)
                audit.action_by = "dmackey"
                audit.action_date = Date.Now
                audit.extension_id = entry.CurrentValues.GetValue(1)
            Next

        End If


    Next
End Sub

结束班

如何保存我创建的这个新对象?在LINQ中,我会做类似的事情:

datasource.object.insertonsubmit(audit)
datasource.SubmitChanges()

1 个答案:

答案 0 :(得分:0)

这是我的最终代码:

Partial Public Class AppsEntities
Private Sub OnContextCreated()
    AddHandler Me.SavingChanges, AddressOf context_SavingChanges
End Sub
Private Shared Sub context_SavingChanges(ByVal sender As Object, ByVal e As EventArgs)
    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 = "dmackey"
                audit.action_date = Date.Now
                audit.extension_id = entry.CurrentValues.GetValue(0)
                context.AddToHistories(audit)
                context.SaveChanges()
            Next

        End If

    Next
End Sub

End Class

基本上,我必须做的是:

  • 在我的ForEach中定义了一个新的AppsEntities实例(“上下文”),
  • 然后我必须将审计对象添加到当前AppEntities(“context”)中的历史记录中。
  • 最后,我必须告诉上下文(“AppsEntities”)将更改保存到数据库中(停止将其保存在EF云中)。
相关问题