简体   繁体   中英

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM