简体   繁体   中英

Deleting object with child entries from database

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?

您需要在定义数据库模式时设置级联删除(如果使用数据库优先,请在数据库中设置;如果使用代码优先,请在EF5上查看EF5代码优先级联 ),或者像执行操作时手动删除(通过这种方式)无需每次都调用SaveChanges())。

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