0

我正在学习 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 条目”

4

3 回答 3

0

您正在发布一个视图模型,该模型与您的实体框架断开连接,并试图告诉 EF 它已更改——它不知道。试试这样的东西,

var obj = yourContext.UserProfiles.Single(q=>q.Id==userProfile.Id);
obj = userprofile;  // ... Map userprofile to the tracked object, obj
yourContext.SaveChanges();
于 2013-06-10T14:25:07.573 回答
0

看起来您没有从视图传递IdUserProfile控制器。你应该添加

@Html.HiddenFor(model => model.Id)

到您的表格

于 2013-06-10T18:06:41.373 回答
0

尝试这个:

if (ModelState.IsValid)
{
    db.UserProfiles.Attach(userProfile);
    db.SaveChanges();

    return RedirectToAction("Index");
}
于 2013-06-10T14:42:25.977 回答