ASP.NET MVC – Attaching an entity of type ‘MODELNAME’ failed because another entity of the same type already has the same primary key value

Problem SOLVED!

Attach method could potentially help somebody but it wouldn’t help in this situation as the document was already being tracked while being loaded in Edit GET controller function. Attach would throw exactly the same error.

The issue I encounter here was caused by function canUserAccessA() which loads the A entity before updating the state of object a. This was screwing up the tracked entity and it was changing state of a object to Detached.

The solution was to amend canUserAccessA() so that the object I was loading wouldn’t be tracked. Function AsNoTracking() should be called while querying the context.

// User -> Receipt validation
private bool canUserAccessA(int aID)
{
    int userID = WebSecurity.GetUserId(User.Identity.Name);
    int aFound = db.Model.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();

    return (aFound > 0); //if aFound > 0, then return true, else return false.
}

For some reason I couldnt use .Find(aID) with AsNoTracking() but it doesn’t really matter as I could achieve the same by changing the query.

Hope this will help anybody with similar problem!

Leave a Comment