编辑不更新数据库

时间:2016-07-19 14:21:56

标签: c# asp.net-mvc asp.net-mvc-4

我有一个MVC应用程序。我遇到了Edit方法的问题。它不会回发到数据库。我添加了断点并逐行执行,值似乎更新但它没有更新数据库。数据库没有主id字段,但其他字段(用户名,服务,short_plan,角色)都是PK。想法?

型号:

[MetadataType(typeof(Department_RolesMetadata))]
public partial class Department_Roles
{
}

public class Department_RolesMetadata
{
    [Required]
    public string username { get; set; }
    [Required]
    public string service { get; set; }
    [Required]
    public string short_plan { get; set; }
    [Required]
    public string role { get; set; }
}

控制器:

 public ActionResult Edit(string username, string service, string sp, string role)
    {
        Department_Roles department_roles = db.Department_Roles.Where(dr => dr.username == username && dr.service == service && dr.short_plan == sp && dr.role == role).First();
        ViewBag.username = new SelectList(db.Service_Logins, "username", "user_type", department_roles.username);
        return View(department_roles);
    }



    [HttpPost]
    public ActionResult Edit(Department_Roles department_roles)
    {
        if (ModelState.IsValid)
        {

            db.Department_Roles.Attach(department_roles);
            db.Entry(department_roles).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.username = new SelectList(db.Service_Logins, "username", "user_type", department_roles.username);
        return View(department_roles);
    }

查看:

 @model NS.Models.Department_Roles

@{
    ViewBag.Title = "Edit";
 }

<h2>Edit</h2>

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Department</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.username)
       </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.username,NS.Models.Department_Roles.GetServiceLogins(),"--Select One--")
        @Html.ValidationMessageFor(model => model.username)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.service)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.service,NS.Models.Service_Logins.GetUserCompetitionTypes(),"--Select One--")
        @Html.ValidationMessageFor(model => model.service)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.short_plan)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.short_plan,NS.Models.FeeAuth.GetActiveShortPlans(),"--Select One--")
        @Html.ValidationMessageFor(model => model.short_plan)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.role)
    </div>
    <div class="editor-field">
        @Html.DisplayFor(model => model.role)
        @Html.HiddenFor(model => model.role)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

 <div>
    @Html.ActionLink("Back to List", "IndividualIndex", new { username = Model.username })
</div>

3 个答案:

答案 0 :(得分:1)

SQL PRIMARY KEY约束: PRIMARY KEY约束唯一标识数据库表中的每条记录。 主键必须包含UNIQUE值。 主键列不能包含NULL值。 大多数表应该有一个主键,每个表只能有一个主键。所以当你编辑你的精华时,你实际上是创造了一个新的!如果所有四个字段都是主键它是复合主键。您没有复合键之外的任何字段。

答案 1 :(得分:0)

这不起作用的原因是您尝试更新数据库中记录的主键值。使用实体框架更新PK值是不可能的,因为它们用于识别记录。

我建议将Id字段作为主键,如果您需要先前选择作为主键的列是唯一的,则添加唯一约束< / em>到使用这些列的数据库。这样您就可以更新这些值,因为它们将不再是PK值,并且您将拥有唯一的约束来保持数据的完整性。

Id课程添加Department_Roles值,并将您的PK更改为仅使用此值:

public class Department_Roles
{
    // New Id value, this will be the primary key
    public int Id { get; set; }

    // ...
}

然后您可以编写类似这样的内容来检索,检查存在所选Id值的记录,然后更新该行:

// Get an entity with all the required PK values
// In your example this will be the posted Department_Roles object
var departmentRole = new Department_Roles() { Id = 1 };

// Get the existing entry from the database
var existingDepartmentRole = dbContext.Department_Roles.Find(departmentRole.Id);

if (existingDepartmentRole == null)
{
    throw new Exception("The existing department role could not be found using the PK values provided");
}
else
{
    // Update the entry that we got out of the database and update the values
    existingDepartmentRole.username = "bob";
    existingDepartmentRole.role = "ProjectManager";
    existingDepartmentRole.service = "Management";
    existingDepartmentRole.short_plan = "permanant";

    // Save the changes
    dbContext.SaveChanges();
}

答案 2 :(得分:0)

您是否尝试从数据库中获取对象的旧值并使用EF的dbContext.Entry(oldObject)。CurrentValues.SetValues(updatedValues)并在此之后调用SaveChnages? 这个microsoft article解释了如何使用该方法。