Kevin Salicos
Kevin Salicos

Reputation: 25

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?

Upvotes: 1

Views: 978

Answers (3)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

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.

Upvotes: 0

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

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.

Upvotes: 0

Nick Olsen
Nick Olsen

Reputation: 6369

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.

Upvotes: 1

Related Questions