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

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);

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.

Leave a Comment