1
Vote

Cannot attach an entity that already exists

description

I am not sure because i have no time to test, but you added this code in new version :
                    // If the entity's state is new, LINQ to SQL Tries to attach an FK references as "New" as well.
                    // To avoid this, attach all FK references first as unmodified (unless they were intended to be new anyway) 
                    // then attach the new record.
                    foreach (PropertyInfo fkPropInfo in _cacheAssociationFKProperties[entity.GetType()].Values)
                    {
                        LINQEntityBase fkProp = fkPropInfo.GetValue(entity, null) as LINQEntityBase;
                        if (fkProp != null && fkProp.LINQEntityState != EntityState.New)
                        {                                
                            try
                            {
                                targetDataContext.GetTable(fkProp.GetType()).Attach(fkProp, false);
                            }
                            catch
                            {
                                // do nothing as the entity was already attached.
                            }
                        }
                    }
=> the problem is that the parent is attached twice if the parent is EntityState.Original (you have a catch, but in my case, the parent came later in the loop)
I think you need more complex code :
  • need to track already attached entity,
  • and the parent can be modified, thus you need attach(current,old) in place of attach(current,false)
    I think my problem came from my child entity has two parent !!

comments