An object with the same key already exists in the ObjectStateManager. The ObjectStateManager can not track multiple objects with the same key

1

I have a problem with a bit annoying, 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 can not track multiple objects with the same key.

From what I found on the internet has something related to the instance of my context, I tried to make a new instance but it still did not work.

Follow 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);
    }
    
asked by anonymous 13.03.2015 / 20:32

1 answer

3

This is because you are selecting the user multiple 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 objects "in one mode only reading". By making these changes, your code should work normally.

    
13.03.2015 / 20:38