0

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?

bbusdriver
  • 1,577
  • 3
  • 26
  • 58
  • You view does not have a form control for `WorkingDateTimeId` do its the default `0`. Just another reason why you never use data models. Always use view models. [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Jul 03 '16 at 08:15
  • Thanks for your comment. But I mean when I post it, workingdatetimeid is automatically assigned. So I was expecting the update would do the same. – bbusdriver Jul 03 '16 at 08:50
  • Your editing - you need to update an existing `WorkingDateTime` but you do not post a value for its ID, so its `0` (your server can't guess what it is). But in any case always use a view model. –  Jul 03 '16 at 08:53

0 Answers0