EntityFramework: How to configure Cascade-Delete to nullify Foreign Keys

后端 未结 2 963
萌比男神i
萌比男神i 2020-12-05 04:22

EntityFramework\'s documentation states that the following behavior is possible:

If a foreign key on the dependent entity is nullable, Code First does

2条回答
  •  自闭症患者
    2020-12-05 04:56

    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().Include(m => m.Children)
            .SingleOrDefault(m => m.Id == 1);
        dbContext.Set().Remove(master);
        dbContext.SaveChanges();
    }
    

    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.

提交回复
热议问题