Error System.Data.Entity.Infrastructure.DbUpdateConcurrencyException while doing update with entity

1

Good morning.

I need to do an update via entity and it accuses me of the following error:

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. 

controller code

 // GET: AreaClientes/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Protocolo protocloLatam = db.Protocolos.Find(id);
            if (protocloLatam == null)
            {
                return HttpNotFound();
            }
            PopulaTipo(protocloLatam.Id);
            PopulaArea(protocloLatam.Id);
            PopulaClassificacao(protocloLatam.Id);
            PopulaAtividade(protocloLatam.Id);
            PopulaCidades(protocloLatam.Id);
            PopulaDestinatarios(protocloLatam.Id);



            // ViewBag.GAreaClienteId = new SelectList(db.GAreaClientes, "Id", "Descricao", areaCliente.GAreaClienteId);
            return PartialView(protocloLatam);
        }
[WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public JsonResult Editar() //[Bind(Include = "Id,Area,GAreaClienteId")] 
        {
            if (ModelState.IsValid)
            {
                Protocolo protocolo = new Protocolo();
                protocolo.ColaboradorId = int.Parse(Request.QueryString["IdColaborador"]);
                protocolo.DestinatarioId = int.Parse(Request.QueryString["DestinatarioId"]);
                protocolo.OrigemId = int.Parse(Request.QueryString["OrigemId"]);
                protocolo.ClassificacaoId = int.Parse(Request.QueryString["ClassificacaoId"]);
                protocolo.ContaContabilId = int.Parse(Request.QueryString["ContaContabilId"]);
                protocolo.AcaoSolicitaId = int.Parse(Request.QueryString["AcaoSolicitaId"]);

                db.Entry(protocolo).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { resultado = true});
            }
            else
            {
                IEnumerable<ModelError> erros = ModelState.Values.SelectMany(item => item.Errors);

                return Json(new { resultado = false, mensagem = erros });
            }
        }

ajax code that triggers the function

$("#btnEditar").on('click', function () {
    var erros = 0;
    $("div").find('*').each(function () {
        var classe = $(this).attr("class");
        if (classe !== undefined) {
            var numItems = $('.has-error').length;
            if (numItems > 0) {
                return false;
            }
            else {

                $.ajax({
                    type: 'GET',
                    url: 'ProtocoloLatam/Editar',
                    dataType: 'JSON',

                    data: {
                        IdColaborador: $("#lblColaborador").attr("data-idColaborador"),
                        DestinatarioId: $("#ColaboradorId").val(),
                        OrigemId: $("#OrigemId").val(),
                        ClassificacaoId: $("#ClassificacaoId").val(),
                        ContaContabilId: $("#ContaContabilId").val(),
                        AcaoSolicitaId: $("#AcaoSolicitaId").val(),
                    }, success: function (data) {

                        $("#minhaModal").modal('hide');

                    }
                }).done(function () {
                    toastr.success("Editado com sucesso.");
                    setTimeout(4000);
                    window.location.reload();
                });
                return false;

            }
        }

    });
});
    
asked by anonymous 01.08.2018 / 13:43

1 answer

1

Your problem is that you retrieve the object with Entity FrameWork, but when you are returning it it does not inform the object's primary key.

  db.Entry(protocolo).State = EntityState.Modified;

Also remember that for you to do the above code the object still has to be mapped to EF in the next, so it would be best to look at the local context and check if it already exists.

var localProtocolo = Contexto.Set<Protocolos>().Local.FirstOrDefault(x => x.Codigo == protocolo.Codigo);
if (localProtocolo != null)
{
    localProtocolo = protocolo;
}

See the example

    
01.08.2018 / 15:18