IEntityChangeTracker的多个实例不能引用实体对象?

时间:2011-09-22 17:51:23

标签: entity-framework

   Private WorkOrderServicesController As New WorkOrderServicesController

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

            Dim _WorkOrderServices As New WorkOrderServices
            _WorkOrderServices.Quantity = 1
            _WorkOrderServices.ServiceID = 1
            _WorkOrderServices.UnitCost = 10
            _WorkOrderServices.CreatedBy = StateManager.UserID
            _WorkOrderServices.CreatedDate = Now

             lstWorkOrderServices.Add(_WorkOrderServices)

            grdServices_Fill()

    End Sub
Protected Sub grdServices_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdServices.RowCommand
    If (e.CommandName.Equals("Delete")) Then
        Dim ServiceID = e.CommandArgument
        Dim _WorkOrderService = lstWorkOrderServices.Where(Function(os) os.ServiceID = ServiceID).SingleOrDefault


        If Not _WorkOrderService Is Nothing Then
            If _WorkOrderService.iWOServicesID > 0 Then
                With _WorkOrderService
                    .Deleted = True
                    .DeletedBy = StateManager.UserID
                    .DeletedDate = Now
                End With

                WorkOrderServicesController.UpdateWorkOrderService(_WorkOrderService)
            Else
                lstWorkOrderServices.Remove(_WorkOrderService)
            End If

        End If
    End If
End Sub

一旦我通过UI将EntityObject传递给DAL并尝试更新实体,面对错误“实体对象不能被多个实例引用” ** MyDAL.DLL **

Public Class WorkOrderServicesDAL
    Private _context As LAITEntities

    Public Sub New()
        _context = New LAITEntities
    End Sub

    Function UpdateWorkOrderService(ByVal vWorkOrderService As WorkOrderServices) As Boolean
        Try
            'An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
            _context.WorkOrderServices.Attach(vWorkOrderService)
            _context.ObjectStateManager.ChangeObjectState(vWorkOrderService, EntityState.Modified)
            _context.SaveChanges()
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

End Class

1 个答案:

答案 0 :(得分:4)

您可能正在DAL中创建ObjectContext,将返回的对象传递到UI中(此时用于检索对象的ObjectContext超出范围),然后传递将对象重新导入DAL,您可以在其中创建另一个 ObjectContext并尝试使用此新上下文保存更改。

你不能这样做;您需要保留原始上下文,并重新使用它(可能通过对象上的实例成员)来保存更改,或者您需要从第一个上下文实例中分离对象并将其重新附加到新的背景。有关附加和分离的详细信息,请参阅此link