This is a problem that has been cropping up for months and is proving to be extremely frustrating.
I have an entity ... StorageContract ... which inherits from Contract; created from a TPT (Table per Type) relationship (I am not sure if that makes a difference). When I attempt to update an existing StorageContract by passing an updated definition of the contract to the Update method ...
public StorageContract UpdateStorageContract(StorageContract contract)
{
Context.ObjectContext.ApplyCurrentValues("Contracts", contract);
Context.SaveChanges();
return contract;
}
... I get the error ...
"An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager"
I found the following post ... "An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager" ... which led me to try "attaching" the contract parameter.
public StorageContract UpdateStorageContract(StorageContract contract)
{
Context.ObjectContext.AttachTo("Contracts", contract);
Context.SaveChanges();
return contract;
}
... Which results in an error that seems to be confusingly quite the opposite of the previous error ...
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
The first error indicated that the entity could not be updated because it could NOT be found ... where as this one seems to suggest that it cannot be updated because it already exists(??). Anyway that led me to the following post ... "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key". SO I reworked the code again based on that ...
public StorageContract UpdateStorageContract(StorageContract contract)
{
var origEntry = Context.Entry<StorageContract>(contract);
if (origEntry.State == System.Data.EntityState.Detached)
{
var set = Context.Set<StorageContract>();
StorageContract attachedEntity = set.Find(contract.Id);
if (attachedEntity != null)
{
var attachedEntry = Context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(contract);
}
else
{
origEntry.State = System.Data.EntityState.Modified;
}
}
Context.SaveChanges();
return contract;
}
Which results in the same error ...
"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
I am chasing this down a rabbit hole that caves in at every turn! I am desperate for help with this!!
Thanks!