I am working on a windows forms app, Entity Framework, I have an error when doing the Update.
public void Update(T entity)
{
//Context.Set<T>().Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
TrySaveChanges();
}
Error: Placement of an entity of type 'POS.Domain.Tallas' failed because another entity of the same type already has the same primary key value. This can occur when the 'Attach' method is used or the state of an entity is set to "No change" or "change" if any entity in the chart has conflicting fundamental values. This may be because some entities are new and have not yet received the generated database key values. In this case, use the 'Add' method or 'added' entity state to trace the chart below, set the state of non-new entities to "Unchanged" or "modified", as appropriate.
You have to see how the Context is configured
public BaseRepository(PosContext context,
bool autoDetectChangesEnabled = false,
bool proxyCreationEnabled = false)
{
this.Context = context;
this.Context.Configuration.AutoDetectChangesEnabled = autoDetectChangesEnabled;
this.Context.Configuration.ProxyCreationEnabled = proxyCreationEnabled;
}
I check if there is a record in the db
public class TallaRepository : BaseRepository<Talla>, ITalla<Talla>
{
public TallaRepository(
bool autodetectChangesEnabled = false,
bool proxyCreationEnabled = false) : base(
new PosContext(),
autodetectChangesEnabled, proxyCreationEnabled)
{ }
public bool Existe(int codigo)
{
int result = Context.Tallas.Where(x => x.TallaId == codigo).Count();
if (result == 0)
return false;
else
return true;
}
}
According to that result I do the Update or Create
public void Create(Talla entity)
{
if (_tallaRepository.Existe(entity.TallaId))
_tallaRepository.Update(entity);
else
_tallaRepository.Create(entity);
}
I have the error in the Update that I show you lines above