父-子表,为现有父记录添加子记录,错误地添加新的父记录,然后添加子记录

本文关键字:记录 添加 然后 错误 子表 | 更新日期: 2023-09-27 18:04:57

在EF我有两个表(父是Office-子是Employee),我添加记录到员工与现有的Office记录的参考,但我猜,由于我的错误配置EF的行为疲倦。

不使用Office表的现有记录,而是在Office中添加新记录,并在子记录中使用新记录的id作为外键,然后创建子记录。

这是我的模型:

public class Office
    {
        public int OfficeId{ get; set; }
        public string Name { get; set; }           
        public virtual IEnumerable<Employee> Employees{ get; set; }
    }

 public class Employee
    {
        public int EmployeeID{ get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DOB { get; set; }
        [NotMapped]
        public int Age { get { return DOB.YearsFromUtcDateTillToday(); } }
        [NotMapped]
        public string FullName { get { return string.Concat(FirstName, ' ', LastName); } }
        public virtual Office Office { get; set; }
    }

视图是Employee的强类型,下面是视图代码:

@model Employee
@{
    ViewBag.Title = "AddEmployee";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm(MVC.CodeTest.AddEmployee(),FormMethod.Post)) {
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model=>model.Office.OfficID)
    <fieldset>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.DOB)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.DOB)
            @Html.ValidationMessageFor(model => model.DOB)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.GPA)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.GPA)
            @Html.ValidationMessageFor(model => model.GPA)
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

我的控制器动作如下:

 public virtual ActionResult AddEmployee(int officeId)
        {
            Employee st = new Employee();
            st.Office=new Office();
            st.Office.OfficeID= officeId;
            return View(st);
        }
        [HttpPost]
        public virtual ActionResult AddEmployee(Employee objEmployee)
        {
           bool success= classEmployeeService.AddEmployee(objEmployee);
            if (success)
            {
                return RedirectToAction("Index",objEmployee.Office.OfficeId);
            }
            else
            {
                ModelState.AddModelError("", "Error! Business rule violation, can't repeat surname");
            }
            return View(objEmployee);
        }
我发现

: 在第一个动作(没有HttpPost)中,OfficeId是正确的,在这种情况下是1检查html我知道它是正确的但是,当按下保存按钮的第二个动作与HttpPost执行OfficeId值是错误的,它是新的Office记录id(18,19或下一个记录)

请指导和帮助我。

父-子表,为现有父记录添加子记录,错误地添加新的父记录,然后添加子记录

我看你的模型设计有问题。Employee类应该有一个属性来表示OfficeID的外键。

public class Employee
    {
        public int EmployeeID{ get; set; }
        public int OfficeID{ get; set; } // This what you need
        // ...... the rest of class properties 
    }

然后把Office Id赋给这个属性而不是导航属性"Office"

Employee st = new Employee();    
st.OfficeID= officeId;

永远不要使用st.Office=new Office();,因为这会将该对象添加到DbContext StateManager中作为"已添加",并将其作为新记录添加到数据库中。