I have a base repository where I only run CRUD. When working with one die at a time, it works normally. However, I needed to make a modification and send several records
to be edited at once. But in doing so, I get an error.
When you click on the refresh button, it searches the data for Id
, and reaches the Update
method with all the data to update, including the ID. As can be seen in the image below:
However,whenIgettolineDbSet.Attach(obj);
Igetthefollowingerror:
Attachinganentityoftype'PrestacaoWeb.Domain.Entities.Prestacao'failedbecauseanotherentityofthesametypealreadyhasthesameprimarykeyvalue.Thiscanhappenwhenusingthe'Attach'methodorsettingthestateofanentityto'Unchanged'or'Modified'ifanyentitiesinthegraphhaveconflictingkeyvalues.Thismaybebecausesomeentitiesarenewandhavenotreceiveddatabase-generatedkeyvalues.Inthiscaseusethe'Add'methodorthe'Added'entitystatetotrackthegraphandthensetthestateofnon-newentitiesto'Unchanged'or'Modified'asappropriate.
Lookingat this question I noticed that the problem is similar, but I did not understand the answer, and how to apply here.
My Entity looks 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, looks 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% generic%:
public void Update(TEntity obj)
{
var entry = Context.Entry(obj);
DbSet.Attach(obj);
entry.State = EntityState.Modified;
}