更新时间:2023-02-03 08:29:37
它确实如描述的那样工作,但有关MSDN的文章却没有强调它仅在将子级加载到上下文中时有效同样,不仅是父实体。因此,除了使用 Find
(仅加载父级)外,还必须使用 Include
(或其他任何项)进行快速加载将子级加载到上下文中的方式):
It works indeed as described but the article on MSDN misses to emphasize that it only works if the children are loaded into the context as well, not only the parent entity. So, instead of using Find
(which only loads the parent) you must use eager loading with Include
(or any other way to load the children into the context):
using (var dbContext = new TestContext())
{
var master = dbContext.Set<TestMaster>().Include(m => m.Children)
.SingleOrDefault(m => m.Id == 1);
dbContext.Set<TestMaster>().Remove(master);
dbContext.SaveChanges();
}
这将从数据库中删除主数据库,在 Child
实体为 null
实体,并将子项的UPDATE语句写入数据库。
This will delete the master from the database, set all foreign keys in the Child
entities to null
and write UPDATE statements for the children to the database.