Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value

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;
}
like image 636
javad hemati Avatar asked Dec 29 '16 08:12

javad hemati


2 Answers

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.

like image 128
Nitish Katare Avatar answered Sep 20 '22 12:09

Nitish Katare


If you are selecting some data in between Update operation (as i was getting problem). Don't use .ToList() or .Find() .... Instead of that use as IQueryable , then use .AsNoTracking()..... Problem solved.

like image 28
Sohail Akhter Avatar answered Sep 16 '22 12:09

Sohail Akhter