Delete child objects in Entity Framework

丶灬走出姿态 提交于 2019-12-03 04:22:29

The reason for that is because as you delete the objects from the context, EF is actively update the Regs navigation property count which means the detail.Regs collection is being changed during the foreach loop which always cause the exception you are getting.

You can create a new collection object and keep deleting from it like this:

foreach (var reg in detail.Regs.ToList())
{
    this.db.Regs.DeleteObject(reg);
}

Or even you can make it cleaner by using LINQ ForEach method:

detail.Regs.ToList().ForEach(r => db.Regs.DeleteObject(r));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!