在EF我有两个表(父亲是Office-子是员工),我在参考现有Office记录时向Employee添加记录,但我想因为我的错误配置,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或下一个记录)
请指导和帮助我。
答案 0 :(得分:0)
我认为您的模型设计存在问题。 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分配给此属性,而不是分配给导航属性&#34; Office&#34;
Employee st = new Employee();
st.OfficeID= officeId;
永远不要使用st.Office=new Office();
,因为这会将此对象添加到DbContext StateManager中,因为&#34;已添加&#34;并将其作为新记录添加到数据库中。