Using MVC4 and EF5 codefirst. Got a problem whereby when creating a new data record with reference to a row with a foreign key. Listing created entries everything looks fine:
@foreach (var item in Model) {
@Html.DisplayFor(modelItem => item.Location.name)
@Html.DisplayFor(modelItem => item.Action.name)
...
Creating a new record the reference fails to display the foreign content (names):
...
@Html.LabelFor(model => model.locationID)
@Html.DisplayFor(model => model.Location.name)
@Html.LabelFor(model => model.actionID)
@Html.DisplayFor(model => model.Action.name)
...
The foreign keys are correctly filled in the controller (see simplied example)
public ActionResult Create()
{
Timerecord tm = new Timerecord();
tm.currentTime = DateTime.Now;
tm.locationID = 1;
tm.actionID = 5;
ViewData.Model = tm;
return View();
}
and the record is correctly created in the database. Just the names are not displayed on the view. Do I have to fetch the associated reocrd myselfs during the Create?
I don’t see any calls to
SaveChanges()in your code. You need to invoke this in order for the foreign key properties to load the navigation properties. Either that or, like you said at the end of your question, load them explicitly.