The ObjectStateManager already has an object with the same key. The status of the existing item is Unchanged.

.net entity-framework

Question

I'm attempting to put into database TB FOO a list of entities of the type 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

There are two relationships in the foo object. One refers to the object TB FOO2 that was just entered into the code, while the other refers to TB FOO3 that was chosen from the database.

the loop's first iteration, when it reaches_MyEntityManager.AddToTB_FOO(foo) It makes the mistake.

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

Any suggestions as to why this error is generated?

1
3
11/8/2010 10:03:31 AM

Accepted Answer

Most likely, you are using an outdatedObjectContext .

This phrase:

_MyEntityManager.AddToTB_FOO(foo)

If an entity already exists with the same primary key value as, the operation will fail.foo in the situation. It won't succeed iffoo is connected to another entity that is unattached but has a "twin" entity in the context with the same primary key value through a navigation property.

Use a new one since it is the easiest method to avoid these issues.ObjectContext for the whole technique and to discard it when you're through Long-livedObjectContext s virtually always result in memory leaks and very perplexing issues.

8
11/8/2010 2:02:51 PM

Popular Answer

I'm using this since I've already created a new instance and filled in the necessary attributes.

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

It seems that this is a newer version of EF or perhaps a different model. It is also mostly translated from C#, so perhaps that is helpful.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow