Trying to get familiar with EF model, but I am having trouble at this point - foreign key problem.
So I have two models.
public class Employee
{
[Key]
public int EmpId { get; set; }
public string Name { get; set; }
public int WorkingDateTimeId { get; set; }
public virtual WorkingDateTime WorkingDateTimes { get; set; }
}
public class WorkingDateTime
{
[Key]
public int WorkingDateTimeId { get; set; }
public string Day { get; set; }
}
Creating Employee information works fine. So in my create view, I enter Employee Name, and WorkingDateTime information, which surprised me it automatically creates a row in WorkingDateTime table.
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.WorkingDateTimes.Day, "Day: ", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.WorkingDateTimes.Day, new { htmlAttributes = new { @class = "form-control" } })
</div>
</div>
However, when I try to edit the specific Employee row, I get this error:
Cannot add or update a child row: a foreign key constraint fails ("test"."employees", CONSTRAINT "FK_Employees_WorkingDateTimes_WorkingDateTimeId" FOREIGN KEY ("WorkingDateTimeId") REFERENCES "workingdatetimes" ("WorkingDateTimeId") ON DELETE CASCADE O)
I am binding these properties in my controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "EmpId,Name,WorkingDateTimes")] Employee employee)
What do I need in order to Edit successfully?