I'm having trouble updating a model, the code below is working correctly when I give GET in a context model edit on the screen (View) and give a submit all ok but when I have a data grid where I load several messages and for example I will check (checkbox) in this grid to change a flag from active to inactive it does not proceed but also not from error?
I think it has to do with ObjectStateManager in all actions that it correctly executes State is with Datached but when it does not update without giving any error State is Unchanged.
A good note to anyone who can help me is that this method always turns with the ID of my Model it is only used for Edit and to insert I have another method.
Follow the method
public void Edit(TEntity entity)
{
var entry = _context.Entry<TEntity>(entity);
var pkey = _dbSet.Create().GetType().GetProperty("ID").GetValue(entity);
if ((entry.State == EntityState.Detached))
{
var set = _context.Set<TEntity>();
TEntity attachedEntity = set.Find(pkey);
if (attachedEntity != null)
{
var attachedEntry = _context.Entry(attachedEntity);
attachedEntry.CurrentValues.SetValues(entity);
}
else
{
entry.State = EntityState.Modified;
}
}
try
{
_context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
StringBuilder sb = new StringBuilder();
foreach (var failure in ex.EntityValidationErrors)
{
sb.AppendFormat("{0} Falha da validação ", failure.Entry.Entity.GetType());
foreach (var error in failure.ValidationErrors)
{
sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
sb.AppendLine();
}
}
throw new System.Data.Entity.Validation.DbEntityValidationException("Erros da validação da Entidade: " + sb.ToString(), ex);
}
}
Who can give me an exit so that always this method of an independent UPDATE if I came with the State, I am grateful. ha and one more thing I've been messing with and had situations where it gave existing ObjectStateManager error as well.