An object with the same key already exists in the ObjectStateManager. Existing facility is in unchanged state.

I am trying to insert a list of objects of type foo in the table TB_FOO.

    Public Sub Insert(ByVal _lstFoo As List(Of TB_FOO))

    Try
      For i As Integer = 0 To _lstFoo.Count - 1
        Dim foo As TB_FOO = _lstFoo(i)        
        _MyEntityManager.AddToTB_FOO(foo)
      Next
      _MyEntityManager.SaveChanges()
      _MyEntityManager.AcceptAllChanges()
    Catch ex As Exception
      Debug.WriteLine(ex.StackTrace)
    End Try

  End Sub

The foo object has 2 relationships. One of them is for the TB_FOO2 object that was just inserted earlier in the code, and the other is for TB_FOO3, which was selected from the database.

On the first iteration of the loop, when it reaches a value _MyEntityManager.AddToTB_FOO(foo), it throws an error

An object with the same key already exists in the ObjectStateManager. The existing facility is in an unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.

Any ideas why this error is occurring?

+3
source share
2

, ObjectContext.

:

_MyEntityManager.AddToTB_FOO(foo)

... , , foo. , foo - , , "" .

- ObjectContext , . ObjectContext .

+8

, , .

Public Sub Insert(ByVal _lstFoo As List(Of TB_FOO))

Try
  For i As Integer = 0 To _lstFoo.Count - 1
    Dim foo As TB_FOO = _lstFoo(i) 
    ObjectStateEntry ose;  
    Dim key=CreateEntityKey("TB_FOOs",foo); 
    if(ObjectStateManager.TryGetObjectStateEntry(key, out ose)) then
       Dim entity=(TB_FOO)ose.Entity;
       TF_FOOs.Detach(entity);
    end if
    _MyEntityManager.AddToTB_FOO(foo)
  Next
  _MyEntityManager.SaveChanges()
  _MyEntityManager.AcceptAllChanges()
Catch ex As Exception
  Debug.WriteLine(ex.StackTrace)
End Try

End Sub

EF, , . # , , , .

0

Source: https://habr.com/ru/post/1773590/


All Articles