[HOWTO] Auto delete nested relations on EntityFramework on VB.NET

I have been lately writing an application on VB.NET and similar code can be applied to C# too if converted or implemented. So my first issue was when I deleted data from parent, they would just delete and related data to the parent didn’t delete automatically. I worked on similar pattern for datetime auto update on created and updates then I stumbled upon EntityState.Deleted similar to EntityState.Added and EntityState.Modified. I am using Sqlite for a lightweight connection, other connection can be used with DbContext on EFCore.

My use case was similar as 3 tables

  • Modules(id, name, created_at, updated_at)
  • Hardwares(id, module_id, name, created_at, updated_at)
  • Tags(id, hardware_id, name, created_at, updated_at)

Everything was fine until I had to remove the Modules from the database and there were unrelated hardwares and tags in the database that were never to be found by any relation. So, to make it auto remove I had to make a minor tweak on overriding SaveChanges() function.

First let’s define the list of DbSet.

Now with this in hand, the we can auto populate the tables in the database and can be used but for the main part of auto deleting we override the SaveChanges() function as:

If you see the code, I implemented multiple level of removal of related tags and can go any level. If the relation is within same table, it works in similar fashion too.

Hope you find something useful out of this. Happy Coding

Leave a Reply

Your email address will not be published. Required fields are marked *