简体   繁体   English

修改复杂类型EF6 MVC5的列表

[英]modifying List of complex types EF6 MVC5

assuming I have the following: 假设我有以下内容:

public class Employee
    {
        public int EmployeeID { get; set; }
        public string FirstName { get; set; }
        public virtual List<LastName> LastName { get; set; }
    }

 public class LastName
    {
        public int LastNameID { get; set; }
        public new string Value1 { get; set; }
    }

and I have an index page where the model is a list of employees with the following: 我有一个索引页面,其中模型是具有以下内容的员工列表:

@foreach (var item in Model) {
//link to Edit page where I can modify the last names in the list
@Html.ActionLink(item.LastName[someIndex], "Edit", new { id = item.EmployeeID })

and in the controller I have 在控制器中

public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Employee employee)
        {
            if (ModelState.IsValid)
            {
               //EXCEPTION HERE - 
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

and an edit view like this 和这样的编辑视图

@model Testing123.Models.Employee

@{
    ViewBag.Title = "LastName";
}

<h2>Last Names</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @for (int i = 0; i < Model.LastName.Count; i ++)
                {
                    @Html.TextBoxFor(m => m.LastName[i].Value1)

                   //ADDED HIDDEN FOR HERE**** Throwing new exception, see below
                    @Html.HiddenFor(m => m.LastName[i].LastNameID)


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
}

When I submit this edit form, it gives me an exception : 当我提交此编辑表单时,它给了我一个例外:

Attaching an entity of type 'Testing123.Models.LastName' failed because another entity of the same type already has the same primary key value. 附加类型为'Testing123.Models.LastName'的实体失败,因为相同类型的另一个实体已经具有相同的主键值。 This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. 如果图形中的任何实体具有相互冲突的键值,则使用“附加”方法或将实体的状态设置为“不变”或“修改”时,可能会发生这种情况。 This may be because some entities are new and have not yet received database-generated key values. 这可能是因为某些实体是新实体,尚未收到数据库生成的键值。 In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate 在这种情况下,请使用“添加”方法或“已添加”实体状态来跟踪图形,然后根据需要将非新实体的状态设置为“未更改”或“已修改”

Is this the correct way of modifying the List of LastName complex type object? 这是修改LastName复杂类型对象列表的正确方法吗? meaning, If have 4 last names already, and I enter this view, with the text boxes, and each last name is displayed in a text box, and I change the value in the text box, will this update the last names on form submitting? 意思是,如果已经有4个姓氏,并且我进入带有文本框的视图,并且每个姓氏都显示在文本框中,并且我更改了文本框中的值,这将更新表单提交中的姓氏?

EDIT 编辑

After adding the HiddenFor helper, I'm getting the following exception now on db.saveChanges 添加HiddenFor帮助程序后,现在在db.saveChanges上收到以下异常

Store update, insert, or delete statement affected an unexpected number of rows (0). 存储更新,插入或删除语句影响了意外的行数(0)。 Entities may have been modified or deleted since entities were loaded. 自加载实体以来,实体可能已被修改或删除。 Refresh ObjectStateManager entries. 刷新ObjectStateManager条目。

It would be useful to see where the exception is coming from (ie stack trace), but in the absence of that there are a few things I'd point out. 查看异常的来源(即堆栈跟踪)会很有用,但是在没有异常的情况下,我需要指出一些事情。

  1. In the Edit action you check if employee is null after you've already used it to get the LastName property. 在“编辑”操作中,您已经使用employee来获取LastName属性,然后检查employee是否为null。
  2. The Edit view does not (or didn't before the edit) provide any mechanism to link the text boxes it generates back to the model. “编辑”视图不提供(或在编辑之前未提供)将其生成的文本框链接回模型的任何机制。 You should use the Html.TextBoxFor rather than Html.TextBox . 您应该使用Html.TextBoxFor而不是Html.TextBox Also you need to have the LastNameId referenced in an Html.HiddenFor(m => m.LastName[i].LastNameId) (inside the loop, obviously) and the EmployeeId and FirstName in Html.HiddenFor entries (outside the loop) so that when the employee is posted back all of the properties on it and its child collection are round-tripped back to the server. 另外,您还需要在Html.HiddenFor(m => m.LastName[i].LastNameId) (显然在循环内部Html.HiddenFor(m => m.LastName[i].LastNameId)引用LastNameId ,并在Html.HiddenFor条目(在循环外部)中Html.HiddenFor EmployeeIdFirstName 。将员工发回时,其上的所有属性及其子集合都将往返于服务器。
  3. LastName (the type) is not a complex type because it doesn't have a [ComplexType] attribute and it does have a column that will be inferred as the primary key of the table. LastName (类型)不是复杂的类型,因为它没有[ComplexType]属性,并且确实具有将被推断为表的主键的列。 This distinction between complex types and normal EF entities is probably not important to answering the question, though. 但是,复杂类型和普通EF实体之间的区别对于回答这个问题可能并不重要。 Have a look at this article for more information. 请查看本文以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM