I'm trying to update an object in my database, but I keep getting the following error:
System.InvalidOperationException: Attaching an entity of type 'Api.Models.Value' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate. at System.Data.Entity.Core.Objects.ObjectContext.VerifyRootForAdd(Boolean doAttach, String entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, EntitySet& entitySet, Boolean& isNoOperation) at System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity) at System.Data.Entity.Internal.Linq.InternalSet
1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet
1.Attach(Object entity) at System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value) at Api.Repositories.Repository1.Update(TObject TObject) in C:\__PS\AWF Library\Content Templates\Development\Code\Client\Template\Web+Api\Api\Repositories\Repository.cs:line 105 at Api.Services.Service
1.Update(Int32 id, TObject obj) in C:__PS\AWF Library\Content Templates\Development\Code\Client\Template\Web+Api\Api\Services\Service.cs:line 60
this is the update code:
public virtual int Update(TObject TObject) {
var entry = Context.Entry(TObject);
DbSet.Attach(TObject);
entry.State = EntityState.Modified;
if (!shareContext) {
var result = Context.SaveChanges();
return result;
}
return 0;
}
Any clue why this is happening? and how to resolve it?
More info on how my code is structured can be found here: Entity Framework load relation