我知道已经问过很多这样的问题,但我似乎无法理解出了什么问题。这是我的代码:
[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);
}
}
更新实体:
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
我不明白。为什么这不起作用,我该如何解决?