2
I have a base repository where I only perform CRUD. When working with one data at a time, it works normally. However, I needed to make a modification and send several records
to be edited at once. But by doing this, I get an error.
By clicking the refresh button, it looks for the data by Id
, and arrives at the method of Update
with all the data to update, including the Id. As can be seen in the image below:
But when you get to the line DbSet.Attach(obj);
i get the following error:
Attaching an Entity of type 'Prestacaoweb.domain.Entities.Prestacao' 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.
Gazing this question I noticed that the problem is similar, but I didn’t understand the answer, and how to apply here.
My Entity is like this:
public class Prestacao
{
public Prestacao()
{
PrestacaoId = Guid.NewGuid();
}
public Guid PrestacaoId { get; set; }
public string Uf { get; set; }
public string Municipio { get; set; }
public string Orgao { get; set; }
public string NomeEntidade { get; set; }
public string TipoPrestacao { get; set; }
public string Prazo { get; set; }
public string Responsavel { get; set; }
public string Telefone { get; set; }
public string TipoPendencia { get; set; }
public string Observacao { get; set; }
public DateTime DataCadastro { get; set; }
public Guid MesId { get; set; }
public virtual Mes Mes{ get; set; }
}
And my Controller, it’s like this:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Editar(List<PrestacaoViewModel> prestacaoViewModel)
{
if (ModelState.IsValid)
{
foreach (var item in prestacaoViewModel)
{
if (item != null)
{
var prestacao =_prestacaoAppService.ObterPorId(item.PrestacaoId);
_prestacaoAppService.Atualizar(prestacao);
}
}
return RedirectToAction("Index");
}
return View("Index");
}
Method of Update
generic:
public void Update(TEntity obj)
{
var entry = Context.Entry(obj);
DbSet.Attach(obj);
entry.State = EntityState.Modified;
}
In
var entry = Context.Entry(obj)
, there’s some code under the inspector’s box?– Leonel Sanches da Silva
@Ciganomorrisonmendez does not have. I added the full code in the question, I had forgotten it.
– Randrade