我正在学习MVC 4.我使用EF5创建了一个数据库第一个项目。在我的编辑视图中,我想向客户添加产品编号。当我点击保存时,我收到以下消息。我认为这是因为产品表中的产品编号为空,因此无法更新。我可以解决这个问题吗?我添加了我的编辑控件
public ActionResult Edit(int id = 0)
{
UserProfile userprofile = db.UserProfiles.Find(id);
if (userprofile == null)
{
return HttpNotFound();
}
//ViewBag.userId = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.UserId);THIS CREATES A NEW ENTRY IN USERPROFILE TABLE
ViewBag.Device_DeviceID = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.Device);
ViewBag.ShippingDetails_ShippingDetailsID = new SelectList(db.ShippingDetails, "ShippingDetailsID", "Address1", userprofile.ShippingDetails_ShippingDetailsID);
return View(userprofile);
}
//
// POST: /User/Edit/5
[HttpPost]
public ActionResult Edit(UserProfile userprofile)
{
if (ModelState.IsValid)
{
db.Entry(userprofile).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.userId = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.UserId);
ViewBag.Device_DeviceID = new SelectList(db.Devices, "DeviceID", "DeviceIMEI", userprofile.Device);
ViewBag.ShippingDetails_ShippingDetailsID = new SelectList(db.ShippingDetails, "ShippingDetailsID", "Address1", userprofile.ShippingDetails_ShippingDetailsID);
return View(userprofile);
}
“存储更新,插入或删除语句影响了意外的行数(0)。实体可能已被修改或删除,因为实体已加载。刷新ObjectStateManager条目”
答案 0 :(得分:0)
您发布了一个视图模型,它与您的实体框架断开连接,并试图告诉EF它已经更改 - 它不知道。尝试这样的事情,
var obj = yourContext.UserProfiles.Single(q=>q.Id==userProfile.Id);
obj = userprofile; // ... Map userprofile to the tracked object, obj
yourContext.SaveChanges();
答案 1 :(得分:0)
试试这个:
if (ModelState.IsValid)
{
db.UserProfiles.Attach(userProfile);
db.SaveChanges();
return RedirectToAction("Index");
}
答案 2 :(得分:0)
看起来你没有通过Id
的{{1}}
查看控制器。
你应该添加
@ Html.HiddenFor(model => model.Id)
到视图中的表单