ObjectStateManager cannot track multiple objects with the same key

I know many questions like this have already been asked, but I just can't figure out what is wrong. This is my code:

[HttpGet]
public ViewResult Edit(int id)
{
    User user = userRepository.GetAll().FirstOrDefault(x => x.ID == id);

    return View("Edit", user);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(User user)
{
    if (ModelState.IsValid)
    {
        user.Password = HashHelper.GetHash(user.Password);
        if (user.ID == 0) // new user
        {
            User testUser = userRepository.GetAll().FirstOrDefault(x => x.Name.Equals(user.Name));

            if (testUser == null)
                userRepository.AddEntity(user);
            else
            {
                ModelState.AddModelError("", "Deze gebruikersnaam bestaat al");
                return View(user);
            }
        }
        else // edit existing user
        {   
            User tempUser = userRepository.GetAll().First(x => x.ID == user.ID);

            if (!user.Name.Equals(tempUser.Name))
            {
                // naam werd aangepast
                int count = userRepository.GetAll().Count(x => x.Name.Equals(user.Name));

                if (count > 0)
                {
                    ModelState.AddModelError("", "Deze gebruikersnaam bestaat al");
                    return View(user);  
                }

            }

            userRepository.UpdateEntity(user);

        }
        userRepository.SaveChanges();
        return RedirectToAction("Index");
    }
    else
    {
        return View(user);
    }
}

      

UpdateEntity:

public void UpdateEntity(T entity)
{
    var entry = context.Entry(entity);
    if (entry.State == EntityState.Detached)
        context.Set<T>().Attach(entity);

    context.Entry<T>(entity).State = EntityState.Modified;
}

      

This results in an error:

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

      

I do not understand. Why isn't this working and how can I fix it?

+3


source to share


1 answer


there are several problems;

  • Don't call GetAll()

    if you want to get a single object, what if you have thousands of objects in your database. Just implement SingleOrDefault in the repository.

Using:

User testUser = userRepository.FirstOrDefault(x => x.Name.Equals(user.Name));

instead:

User testUser = userRepository.GetAll().FirstOrDefault(x => x.Name.Equals(user.Name));

      



  • After retrieving an existing user from the database, simply update that item with the new values ​​instead of trying to keep the one returned from the page;

use

User tempUser = userRepository.GetAll().First(x => x.ID == user.ID);
tempUser.UserName = user.UserName;
....
SaveChanges();

      

instead of trying to save the user fetched from the page.

  • you need to decide the key of your organization; it's a name, it's an identifier, or both.
+2


source







All Articles