0

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.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) at System.Data.Entity.Internal.Linq.InternalSet1.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.Service1.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

Sefe
  • 13,731
  • 5
  • 42
  • 55
Kiwi
  • 2,713
  • 7
  • 44
  • 82
  • Possible duplicate of [ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value](http://stackoverflow.com/questions/23201907/asp-net-mvc-attaching-an-entity-of-type-modelname-failed-because-another-ent) – Toddams Mar 03 '16 at 12:20
  • Have you set the primary key to auto-increment in the database? – Dumisani Mar 03 '16 at 12:23
  • Where does your attached object come from? Did you create it or did it come from the DB? – Sefe Jun 26 '18 at 08:52
  • Are you performing any .Find() or .Where() operation for verifying that record already exist or not before calling Update() function? If yes then that's the place which cause error. That object which return from that operation needs to be detach before your Update function call. – Karan Jun 26 '18 at 09:34

0 Answers0