我知道很多像这样的问题已经被问过,但我似乎无法理解错误。这是我的代码:
[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;
}
这会导致此错误:
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key
我不明白。为什么这不起作用,我该如何解决?
答案 0 :(得分:2)
存在多个问题;
GetAll()
,如果数据库中有数千个实体,该怎么办?只需在存储库中实现SingleOrDefault。使用:
User testUser = userRepository.FirstOrDefault(x => x.Name.Equals(user.Name));
而不是:
User testUser = userRepository.GetAll().FirstOrDefault(x => x.Name.Equals(user.Name));
使用
User tempUser = userRepository.GetAll().First(x => x.ID == user.ID);
tempUser.UserName = user.UserName;
....
SaveChanges();
而不是试图保持从页面检索的用户。