The ObjectStateManager cannot track multiple objects with the same key

c# entity-framework

Question

I'm aware that similar inquiries have already been made, but I just can't figure out what's wrong. Here's 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 leads to the following error

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

It eludes me. How can I make this work and why doesn't it?

1
3
2/13/2013 8:36:15 AM

Accepted Answer

there are numerous issues;

  • Don't dialGetAll() What if your database has hundreds of entities and you only want to fetch one? Add a SingleOrDefault to the repository.

Use:

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

in place of

User testUser = userRepository.GetAll().FirstOrDefault(x => x.Name.Equals(user.Name));
  • Instead of attempting to persist the item returned by the page after retrieving an existing user from the database, simply update this item with new values;

use

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

rather than making an effort to persist, user retrieved from page.

  • You must choose whether your entity's key is its name, its ID, or both.
2
2/13/2013 8:47:37 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow