I am stuck at a point when my code throw an exception at:
dbContext.Entry(entity).State = EntityState.Modified;
I have been using this code since last month but this exception raises just two days ago. I have read many threads but none benefits me. Problem is when try to update existing record it always display given below error:
Attaching an entity of type 'X' 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.
I have used given below code:
{
if (unitOfWork.AddressRepository.DataSet.Where(x => x.AddressId == item.AddressId).ToList().Count() > 0)
unitOfWork.AddressRepository.Update(item);
else
unitOfWork.AddressRepository.Create(item);
}
public virtual void Update(T entity)
{
dbContext.Entry(entity).State = EntityState.Modified;
}
For testing purpose i also did an experiment with "Update" method.
try
{
dbContext.Entry(entity).State = EntityState.Modified;
}
catch (Exception ex)
{
Create(entity);
}
public virtual void Create(T entity)
{
dbSet.Add(entity);
}
//constructor taking the database context and getting the appropriately typed data set from it
public Repository(DBEntities context)
{
dbContext = context;
dbSet = context.Set<T>();
}
I have filled my dbContext in constructor. So I always get dbContext at start.
Every time Create(entity) method executed which create a new record. When I checked in database, records get duplicated.