context.SaveChanges()有效,但数据库永远不会更新? (MVC 3)

时间:2012-08-02 17:36:32

标签: asp.net-mvc-3

我已经在ASP.NET MVC3中编写了一个表单,但是我无法获得保存我在数据库中所做更改的条目,但在调试时,我注意到这些更改反映在数据上下文。我在运行此代码时遇到错误。如果您需要更多,请告诉我。谢谢!

控制器

[HttpPost]
    public ActionResult Edit(Tool tool, FormCollection collection)
    {
        if (collection["Tool.Person.PersonID"] != "")
        {
            tool.Person= context.People.Find(
                 Convert.ToInt32(collection["Tool.Person.PersonID"])
            );
        }
        if (collection["Tool.Company.CompanyID"] != "")
        {
            tool.Company = context.Companies.Find(
                 Convert.ToInt32(collection["Tool.Company.CompanyID"])
            );
        }

        if (ModelState.IsValid)
        {
            context.Entry(tool).State = EntityState.Modified; 
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(tool);
    }

前两个if语句正在检查用户是否输入了个人或公司,并且信息是通过FormCollection传递的。 PersonID和CompanyID分别是Person和Company的主键。我逐行遍历该方法并获得相同的结果 - 在context.SaveChanges();之后,上下文反映了更改,但是对于Person_PersonID和Company_CompanyID,数据库条目保持为空。

1 个答案:

答案 0 :(得分:1)

尝试使用视图模型并在用户提交表单后访问数据库。

这样可以帮助你顺利完成。

视图模型

using System.ComponentModel.DataAnnotations;

namespace Project.ViewModels
{
    public class _tools
    {
        [Required(ErrorMessage="ToolID is required")]
        public int32 ToolID{ get; set; } //whatever ID you use to retrieve the Tool from the database.

        [Required(ErrorMessage="PersonID is required")]
        public int32 PersonID{ get; set; }

        [Required(ErrorMessage="CompanyID is required")]
        public int32 CompanyID{ get; set; }
    }

}

控制器帖子

[HttpPost]
public ActionResult Edit(_tool viewModel)
{

    if (ModelState.IsValid)
    {
        Tool tool = db.GetTool(viewModel.ToolID) //whatever method you use to get a current version of the row.  You already do this before you send the data to the client, so just copy that code

        tool.Person = viewModel.PersonID
        tool.Company = viewModel.CompanyID

        context.Entry(tool).State = EntityState.Modified; 
        context.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(tool);
}

查看

@model = _tool

@using(Html.BeginForm("Edit", "ControllerNameHere", FormMethod.Post, null))
{
    @Html.HiddenFor(model => model.ToolID)
    @*Also add whatever inputs you use to get PersonID and CompanyID from the user.
      Make sure to either use the @Html helpers or to give them names that correspond.
      i.e. name one input PersonID and the other CompanyID*@

    <input type="submit" value="Edit">

}