I am using MVC4 and EF5 codefirst. I have a problem whereby when creating a new data record with reference to a row with a foreign key, the fields of the foreign key row are set to null.
Here is a simplified scenario:
public class Person
{
string name { get; set; }
Color color { get; set; }
}
public class Color
{
int id { get; set; }
string name { get; set; }
}
The viewmodel:
public class PersonViewModel
{
public Person Person { get; set; }
public IEnumerable<SelectListItem> Colors { get; set; }
public PersonViewModel()
{
Context db = new Context();
Colors = db.Colors.ToList().Select(t => new SelectListItem() { Text = t.Name, Value = t.Id.ToString() });
}
}
The controller:
public ActionResult Create()
{
return View(new PersonViewModel);
}
[HttpPost]
public ActionResult Create(PersonViewModel personViewModel)
{
if (ModelState.IsValid)
{
db.Person.Add(personViewModel.Person);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(personViewModel);
}
and finally, the create view:
@model PersonViewModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Person.Name)
@Html.EditorFor(model => model.Person.Name)
@Html.LabelFor(model => model.Person.Color)
@Html.DropDownListFor(model => model.Person.Color.Id, this.Model.Colors)
<input type="submit" value="Create" title="Create ticket" />
}
Say I have two colors in the data:
1. red
2. blue
When creating a new person through the view and selecting blue as the color, the person will be created correctly but ‘blue’ with id 2 in color table will maintain its ID (of 2) but its name will have been set to empty.
Im sure there is a binding issue occurring here? Should this be supported as standard in the framework or do I need to create my own modelbinder?
Thanks
So it turns out I wasn’t correctly following entity framework conventions. By explicitly defining the foreign key column, entity framework correctly recognises the relationship and works as I would expect. Therefore, the new data model (adding the explicit foreign key column)
and the updated view (binding on the new foreign key column):