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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With