I cannot get my relationship to save correctly on update/create with Entity Framework 5.
I’ve got a new MVC 4.0 project with EF 5 and I’m using code-first migrations.
My models look like this.
public class Blog
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
public class Post
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Text{ get; set; }
public virtual Blog Blog { get; set; }
}
My migration correctly creates a Blog_Id column in my posts table.
Post Controller:
var db = new AppContext();
ViewBag.Blogs = new SelectList(db.Blogs.ToList(), "ID", "Title", post.Blog_Id);
Post View:
<p>
@Html.LabelFor(model => model.Blog.Id, "Blog")
@Html.DropDownListFor(model => model.Blog.Id,
(SelectList)ViewBag.Blogs, "Select blog", new { })
@Html.ValidationMessageFor(model => model.Blog.Id)
</p>
When I create/update the post though, the model has the correct relationship before saving, but the Blog_Id column does not persist to the database.
My update function looks like this.
var db = new AppContext();
db.Posts.Attach(post);
db.Entry(post).State = EntityState.Modified;
db.SaveChanges();
Any help would be greatly appreciated. All of the documentation and examples I’ve looked at seems to be outdated (mostly uses EF4) and the MSDN docs seem to be self referential (EF say to look at docs, docs say to look at EF site) and difficult to navigate.
The simplest solution is to expose the foreign key as a property in your model:
Then bind your post view to that property:
If you don’t want that you need change tracking to make EF recognize that the relationship has changed: