Please can you tell me where I am wrong. I had a following code:
public void UpdateClient(Client oClient)
{
foreach(Mitarbeiter item in oClient.Mitarbeiters)
{
if (item.MiID==0)
{
context.Mitarbeiters.AddObject(item);
}
else {
var key = context.CreateEntityKey("Mitarbeiters",item);
object original;
if (context.TryGetObjectByKey(key,out original))
{
context.ApplyCurrentValues(key.EntitySetName,item);
}
}
}
context.Clients.First(c => c.ClID == oClient.ClID);
context.Clients.ApplyCurrentValues(oClient);
context.SaveChanges();
}
I received
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
when I add a new object to Mitarbeiters
Assuming that your class
Mitarbeiterhas a navigation property toClientand it is not null when you run through the loop (soitem.Client != null) then by addingitemto the ObjectSet you also add the referencedClientinto the context in stateAdded. (Adding an entity does not only add the entity itself but also all referenced entities which are not yet in the context.) Later (context.Clients.First(c => c.ClID == oClient.ClID);) you load the client a second time which is already in the context inAddedstate which is the reason for the exception.Try to load the client into the context before you add
item:Just a guess, I am not sure if this will solve your problem.