Entity Framework / MVC: Writing a collection to the database
What I have looks something like this:
class foo
{
[Key]
int ID;
List<Bar> bars;
string s;
}
class bar
{
[Key]
int ID;
string s;
}
then in the controller:
public ActionResult BeAwesome(foo doo)
{
db.Entry(doo).State = EntityState.Modified;
db.SaveChanges();
return View(doo);
}
开发者_Go百科
I can confirm that doo is being passed in with a list of bars, but the bars are not being propagated to the database. doo.s does get saved. What do I need to do to get the collection to save?
Have you tried attaching the entity to the context before you set its state?
db.foos.attach(doo);
db.Entry(doo).State = EntityState.Modified;
What happens if you set the state of each bar in the doo to EntityState.Modified? Or possibly attaching each of the bars individually in a loop.
you need to define the properties like this,
public virtual List<Bar> bars{get; set;}
and also you need to define navigational properties as virtual to enable lazy-loading.
The reason is that only foo is set to Modified
- all related bars are in Unchanged
state. You must iterate through bars and set their state as well:
public ActionResult BeAwesome(foo doo)
{
db.Entry(doo).State = EntityState.Modified;
foo.Bars.ForEach(b => db.Entry(b).State = EntityState.Modified);
db.SaveChanges();
return View(doo);
}
Obviously if you have some bars inserted or deleted you need more complex logic to set the state.
精彩评论