An Object with the same key already exists in the Objectstatemanager. The Objectstatemanager cannot track Multiple Objects with the same key

Asked

Viewed 364 times

1

Guys I’m having a bit of a problem, I’m trying to do an update using the Entity Framework, but when it arrives in Savechanges(), the following error appears.

An Object with the same key already exists in the Objectstatemanager. The Objectstatemanager cannot track Multiple Objects with the same key.

From what I found on the internet has something to do with the instance of my context, I tried to make a new instance but it still didn’t work.

Follows the code:

        [HttpPost]
    public ActionResult EditPassword([Bind(Include = "intIDUsuario,strNome,strUsuario,strSenha,bitStatus,strTelefone,strEmail,intIDPerfil,NovaSenha,ConfirmaSenha")] Usuario usuario)
    {
        try
        {

            var query2 = from q in db.Usuario where q.intIDUsuario == usuario.intIDUsuario select q.intIDUsuario;
            int id1 = query2.FirstOrDefault();


            string pass = Cryptography.Encrypt(usuario.strSenha);

            var user = db.Usuario.ToList().Where(x => x.strSenha == pass && usuario.NovaSenha == usuario.ConfirmaSenha).Count() > 0;

            if (user)
            {

                usuario.strSenha = Cryptography.Encrypt(usuario.NovaSenha);

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

                return RedirectToAction("Index","Suporte");
            }

            return RedirectToAction("Index", "Suporte");

        }
        catch
        {

            ModelState.AddModelError("","Ocorreu um erro!!!");

        }

        return View(usuario);
    }

1 answer

3

This is because you are selecting the user several times. By default, the Entity Framework monitors all loaded objects, even if there is no change in them.

To prevent read-only objects from being monitored, use the following:

        var query2 = from q in db.Usuario where q.intIDUsuario == usuario.intIDUsuario;
        int id1 = query2.AsNoTracking().FirstOrDefault().Select(q => q.intIDUsuario);

        string pass = Cryptography.Encrypt(usuario.strSenha);

        var user = db.Usuario.AsNoTracking().Count(x => x.strSenha == pass && usuario.NovaSenha == usuario.ConfirmaSenha) > 0;

AsNoTracking loads the "read-only mode" objects. By making these changes, your code should work normally.

  • On the line var query2 = from q in db.Usuario where q.intIDUsuario == usuario.intIDUsuario select q.intIDUsuario;&#xA;&#xA; int id1 = query2.AsNoTracking().FirstOrDefault(); The following error&#Xa appears;The type 'int' must be a Reference type in order to use it as Parameter’T' in the Generic type or method 'System.Data.Entity.QueryableExtensions.Asnotracking<T>(System.Linq.Iqueryable<T>)'

  • @Diegodias Cara, I forgot to edit the answer for you on the day! Really bad. Now it’s OK.

Browser other questions tagged

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