In my MVC application I have a method, that should add an entity to database (if it is doesn't exist), or update it (if it is already in database)
//...
var list = _context.CurrencyRepository.Get().ToList();
foreach (var currency in currencies)
{
var item = list.FirstOrDefault(c => c.CurrencyId == currency.CurrencyId);
if (item != null)
{
_context.CurrencyRepository.Update(currency);
}
else
{
_context.CurrencyRepository.Add(currency);
}
}
_context.CommitChanges();
//...
public virtual void Update(T entityToUpdate)
{
//both lines fail with the same error message
_dbSet.Attach(entityToUpdate);
_dbContext.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual T Add(T entity)
{
return _dbSet.Add(entity);
}
public void CommitChanges()
{
_dbContext.SaveChanges();
}
It works for adding, but unfortunately I get an error, when I'm trying to update:
Attaching an entity of type 'Currency' 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.
Could anybody explain how should I update my database, please?