I am using Entity Framework 4.0. I am facing problem while updating data in the database. I am getting this exception :
An object with the same key al
Updating a detached object graph can be very difficult. (An example with only one child collection is here: https://stackoverflow.com/a/5540956/270591 If you have a grand child collection it is even more complex.)
There is no generic approach or a simple method like setting the state to Modified
(it only marks scalar properties as changed) and hoping it would store all the object graph changes.
The details to consider to implement such an update:
CourseOptions
of each Menu
.For the (relatively simple) case that a user in your specific ceremony Edit view...
CourseOptions
should be deleted as well and cascading delete for that relationship is enabled in the databaseCourseOptions
to an existing Menu
and cannot delete them from a Menu
CourseOptions
to an new Menu
(and the CourseOptions
should be inserted together with the new menu)CourseOption
...the code would look like this:
var ceremonyInDb = db.Ceremonies.Include(c => c.Menus)
.Single(c => c.Id == ceremony.Id);
db.Entry(ceremonyInDb).CurrentValues.SetValues(ceremony);
foreach (var menuInDb in ceremonyInDb.Menus.ToList())
if (!ceremony.Menus.Any(m => m.Id == menuInDb.Id))
db.Menus.Remove(menuInDb);
foreach (var menu in ceremony.Menus)
if (!ceremonyInDb.Menus.Any(m => m.Id == menu.Id))
ceremonyInDb.Menus.Add(menu);
db.SaveChanges();
If some of the restrictions do not apply (i.e. the user can do more complex modifications in your view) the code will be more complex. But the basic idea is to load the object graph (root and children with Include
and possibly grand children with Include(...Select(...))
) from the database, compare that original graph with your new detached graph and apply changes to the original graph according to the differences to the new graph.