I have an ASP.Net MVC project where I add in a View a student entity to my Entity Framework 6 repository.
class Student
public long Id { get; set; }
public virtual Book Favorite { get; set; }
class Book
public long Id { get; set; }
public string Title { get; set; }
The Favorite
property is set from a drop down in the view.
In the controller on post, only the Id
for the book is set.
To tell Entity Framework, to only add the student, but not to add
the referenced book, I set the EntityState for the Book to Unchanged as
described here
After saving my changes, I have the correct student record in the database and also the book record remains unchanged, but whenever I query now the book from my repository (not via the student), I get a book entity back where only the Id is set and Title and all other properties are null.
My Controller (simplified):
public ActionResult Create()
{
StudentViewModel result = new StudentViewModel();
result.BookList = new SelectList(DbContext.Books, "Id", "Name");
return View(result);
}
[HttpPost]
public ActionResult Create(StudentViewModel viewModel)
{
DbContext.Entry(viewModel.NewStudent.Favorite).State = EntityState.UnChanged);
DbContext.Add(viewModel.NewStudent);
DbContext.SaveChanges();
Book missingProperties =
DbContext.Books.Single(book => book.Id == viewModel.NewStudent.Favorite.Id);
}
My View (simplified):
@using System.Linq
@model StudentViewModel
@using (Html.BeginForm())
{
...
@Html.TextBoxFor(model => model.NewStudent.Name)
@Html.DropDownListFor(model => model.NewStudent.Favorite.Id, Model.BookList)
...
}