System.Data.Entity.Infrastructure.Dbupdateconcurrencyexception error while updating with Entity

Asked

Viewed 110 times

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 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;

            }
        }

    });
});
  • what is in the object db. Entry(protocol) => protocol is from the same key you recovered ? the object is still in the vicinity of EF ? if not this you have to attach it before

  • I noticed that I really needed to pass his id... now it’s giving datetime2 conversion error to datetime.

  • nor will I say that you are not passing the date and he is sending 1901/01/01 hsuahsau

  • 1

    @Marconciliosouza HAHAHAHAHA got it right, I saw it here and it worked kk

1 answer

1

Your problem is that you recover the object with the Entity Framework, but when you are returning it does not inform the primary key of the object.

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

Also remembering that for you to make the code above the object still has to be mapped in the EF next, then the most indicated would be you 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;
}

Take the example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.