C# – Attaching an entity of type ‘X’ failed because another entity of the same type already has the same primary key value

asp.net-mvccentity-framework

ErrorMessage :

Attaching an entity of type 'FaridCRMData.Models.Customer' 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.

My Code:

public class FactorController : Controller
{
    public JsonResult SaveFactor(Factor factor,int id)
    {
        if (id > 0)
        {
            bool result = new FactorService.BaseService.Update(factor);
            return new JsonResult() { Data = result };
        }

    }
}

FactorService.BaseService.cs :

public bool Update(TEntity entity)
{
    var entry = context.Entry(entity);
    if (entry.State == EntityState.Detached || entry.State == EntityState.Modified)
    {

        context.Set<TEntity>().Attach(entity);// Error Is Here
        entry.State = EntityState.Modified;
        context.SaveChanges();
    }
    return true;
}

Best Answer

I believe you might have invoked Select before the update, By default, DBContext will cache the record when they are fethced (Selected), use "AsNoTracking()" in your select call while fetching record.