我试图将实体框架4.1从我MVC3控制器的Edit行动中插入/更新数据,其编码如下:
[HttpPost]
public ActionResult Edit(UserDetailsForm form)
{
try
{
if (ModelState.IsValid)
{
UserProfile up = cpctx.UserProfiles.Where(w => w.UserName.Equals(form.email)).SingleOrDefault();
if (up == null)
{
up = new UserProfile();
up.UserName = form.email;
up.FirstName = form.FirstName;
up.LastName = form.LastName;
ctx.UserProfiles.Add(up);
}
else
{
up.FirstName = form.FirstName;
up.LastName = form.LastName;
cpctx.Entry(up).State = EntityState.Modified;
}
ctx.SaveChanges();
return RedirectToAction("Index");
}
return View(form);
}
catch
{
return View(form);
}
}
Everything works fine for an new record and I get a new row in the database, my problem occurs when updating. The code executes without any exceptions and I can see the values in up
correctly in the watch window, however, when ctx.SavesChanges()
is executed the database is not updated.
Any help in resolving this issue will be greatly appreciated.