"cannot attach an entity that already exists" exception when I adding new objects into a collection

Dec 19, 2011 at 10:09 PM


I adding new objects into a collection inner a root object retrieved from my database.


MyRootObject root_object = GetRootObject(withdetailsitems);


newchild = new ...
root_object.Details[0].ChildObjects.Add(newchild); //Details is a collection inner my root


When I want to save all, I'd like that newchild been saved in the database

void SaveData(MyRootObject root_object){
  //create my new datacontext instance
  root_object.SynchroniseWithDataContext(db, false);

I got an exception in SynchroniseWithDataContext "cannot attach an entity that already exists". It's trying to attach Details[0] object twice. Details[0] have EntityState.Original.


Help me please. Tell me what i am doing bad.


Dec 19, 2011 at 11:22 PM

I had added a validation in LINQEntityBase.cs source code

in SynchroniseWithDataContext method when an entity have the EntityState.Original state

if(entity.LINQEntityState == EntityState.Original)
  if(targetDataContext.GetTable(entity.GetEntityType()).GetOriginalEntityState(entity) == null) //doesn't exist in datacontext
     targetDataContext.GetTable(entity.GetEntityType()).Attach(entity, false);

I taked this solution from http://stackoverflow.com/questions/6493737/how-do-i-check-whether-a-linq-to-sql-object-is-already-attached-to-a-datacontext

Please tell me if this is the best solution.