views:

577

answers:

1

Im trying to get my head around attaching an entity with a related entity to a new context when I want to update the entity.

I have a Person Table (Generalised to Personnel), which has a LanguageID field. This field is linked as a FK via the EF to another table Language with LanguageID as the primary key (1-M). I need to update a particular Persons language preference, however, the relationship seems to remain linked to the old context as i get a "Object cannot be referenced by multiple instances of IEntityChangeTracker" error on the line marked below. Is there any way to attach the Language entity to the new context as a relationship of the Personnel (Person) entity???

The entities were not detached in the orginal GetPersonnel() method which uses an .Include() method to return the PreferredLanguage

PreferredLanguage is the NavigationProperty name on the Person table...

 public static void UpdateUser(Personnel originalUser, Personnel newUser )
    {
        using (AdminModel TheModel = new AdminModel())
        {

            ((IEntityWithChangeTracker)originalUser).SetChangeTracker(null);
            ((IEntityWithChangeTracker)originalUser.PreferredLanguage).SetChangeTracker(null);

            TheModel.Attach(originalUser);--Error Line
            TheModel.ApplyPropertyChanges("Person", newUser);

            TheModel.SaveChanges(); 
        }
    }

Thanks Sean

+1  A: 

To avoid these sort of problems you should make GetPersonnel() do a NoTracking query.

I.e.

ctx.Person.MergeOption = MergeOption.NoTracking;
// and then query as per normal.

This way you can get a graph of connected entities (assuming you use .Include()) that is NOT attached. Note this won't work if you try to manually detach entities, because doing so schreds your graph.

Hope this helps

Alex

Alex James