Bv202
Bv202

Reputation: 4044

The ObjectStateManager cannot track multiple objects with the same key

I'm aware many questions like this one have already been asked, but I just can't seem to understannd 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 this error:

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

I don't get it. Why doesn't this work and how can I fix it?

Upvotes: 3

Views: 6403

Answers (1)

daryal
daryal

Reputation: 14919

there are multiple problems;

  • Do not call GetAll() if you want to fetch a single entity, what if you have thousands of entities in the database. Just implement a SingleOrDefault in the repository.

Use :

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

instead of :

User testUser = userRepository.GetAll().FirstOrDefault(x => x.Name.Equals(user.Name));
  • After fetching an existing user from database, just update this item using new values instead of trying to persist the one returned from page;

use

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

instead of trying to persist user retrieved from page.

  • you need to decide the key of your entity; is it name, is it Id or both.

Upvotes: 2

Related Questions