I like using Entity Framework, but it seems there is one basic piece of functionality it is not good at: cascade deletes. Entity Framework does not issue cascade deletes by default, therefore you can have “orphan” entities still stored when their parent is deleted; their parent Id will simply by nulled out. Therefore, you must explicitly set for entities to be deleted if their parent is deleted, i.e. cascade deleted. I have set up the following domain to illustrate cascade deletes in Entity Framework:
The GrandParent has a list of Parents (its children) and the Parents have a list of GrandChildren (its children). If you would like the Parents to be deleted when the GrandParent (its parent) is deleted, you would use the following code:
modelBuilder.Entity().HasMany(x => x.Children).WithRequired(x => x.MyParent).WillCascadeOnDelete();
But even with this, the GrandChildren (children of the Parent) will not be deleted, but be orphaned, so you will need to set cascade delete on the Parent entity to delete the GrandChildren, and also on the GrandChidlren to delete the Friends (children of the GrandChildren):
modelBuilder.Entity().HasMany(x => x.Friends).WithRequired(x => x.GrandChild).WillCascadeOnDelete();
When you add one of these cascade delete configurations and rebuild the database, Entity Framework will go and set the cascade delete option on the SQL table:
And because Entity Framework sets these cascade delete options in SQL, SQL can effectively handle all the cascade delete for you; therefore, in theory, the only command you need to issue is to delete the GrandParent and all it children will also be deleted. But this will not work in our case as GrandChild is an abstract class and Entity Framework does not set the cascade delete option in SQL (weird right). Instead, Entity Framework will issue a delete statement for each table (even though it sets the cascade delete options in SQL?!). Therefore, if you try deleting a GrandParent, the following delete statements will be executed in SQL:
Whereas it could do this by issue less commands, therefore reducing the bandwidth usage by the SQL server. This seems inefficient. Let’s hope these issues are cleared up in EF Core.