0
Class Student 
{
    public string Name { get; set; }
    public List<Location> Locations { get; set; }
}

The scenario goes like this:

  1. Page is loaded to client with Student using entity framework(EF) 6
  2. List of Locations edited by client by removing one, but another added
  3. Student is posted back to save and auto-bound to the model

I could attach Student back to the EF context using:

context.Entry(Student).Attach();

The problem is that EF will not detect the changes in Locations. I have to:

  1. Save Locations in a new Locations list
  2. Set Student.Locations = null;
  3. Then attach Student to the DbContext
  4. Loop through all Student.Locations and Remove each one
  5. Loop through all the new Locations list that I saved, pull the location from the database, then Add to Student
  6. Finally Save

What a pain. Any ideas?

Ian
  • 2,512
  • 1
  • 20
  • 26
  • 1
    Yeah, that's a pain point that has been noted. https://entityframework.codeplex.com/workitem/864 You will need to implement code like this http://stackoverflow.com/questions/27176014/how-to-add-update-child-entities-when-updating-a-parent-entity-in-ef – Steve Greene Feb 11 '16 at 17:24

1 Answers1

0

You probably better implement different actions independently: IE: one action for adding a location and another action for removing an existing action.

Then you can just call them with ajax to keep user interactivity.

Souhaieb Besbes
  • 1,445
  • 17
  • 30
  • It's more efficient to let the user make changes, then save at the end. It's the whole concept of having these changes detected that's the issue. – Ian Feb 12 '16 at 10:16
  • It really depends on your view of things, but i think separating actions is better in the context of a web app. say for example user made lots of changes and then got a browser crash he will lose all changes. If every change was commited whenver made he will lose at most the last change. Just a quick example to illustrate why this approach might be better – Souhaieb Besbes Feb 12 '16 at 10:28
  • Good point. Then that would mean keeping the data in session whilst it's being edited so EF can track everything. – Ian Feb 12 '16 at 10:33
  • That's another way to do things. but i wouldn't recommend it – Souhaieb Besbes Feb 12 '16 at 13:00