I'm very new to Model First and Entity Framework 4.1, and always created my small databases without relations, and implying those by putting reference fields in the child tables. I tried to give Model First a try and created a database with 3 tables with one to many relationships between each other, so: Grandfather -> Father -> Son
When i try to delete with the following code it doesn't work:
DBUpdateException: An error occurred while updating the entries. See the inner exception for details.
Code:
var toDelete = db.Grandfathers.Find(id);
db.GrandFathers.Remove(toDelete);
db.SaveChanges();
But when i delete them recursively with the following code everything goes well as expected.
db.Grandfathers.Where(g=>g.Id = id).SelectMany(f=>f.Fathers).SelectMany(s=>s.Sons).ToList().ForEach(r => db.Sons.Remove(r));
db.SaveChanges();
db.Grandfathers.Where(g=>g.Id = id).SelectMany(f=>f.Fathers).ToList().ForEach(r => db.Fathers.Remove(r));
db.SaveChanges();
db.Grandfathers.Where(g=>g.Id = id).ToList().ForEach(r => db.Grandfathers.Remove(r));
db.SaveChanges();
How can i delete all the child records from the Grandfather record without going through all of this?
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.