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
.
1 2 3 |
Public Property Modules As DbSet(Of MModule) Public Property Hardwares As DbSet(Of MHardware) Public Property Tags As DbSet(Of MTag) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Public Overrides Function SaveChanges() As Integer Dim entries = ChangeTracker.Entries().ToList entries.Where(Function(e) e.State = EntityState.Deleted And TypeOf e.Entity is MModule).ToList().ForEach(Sub(m) Dim module = DirectCast(e.Entity, MModule) Hardwares.ToList().Where(Function(h) h.module_id = module.id).ToList.ForEach(Sub(h) Hardwares.Remove(h) End Sub) End Sub) entries.Where(Function(e) e.State = EntityState.Deleted And TypeOf e.Entity is MHardware).ToList().ForEach(Sub(m) Dim hardware = DirectCast(e.Entity, MHardware) Tags.ToList().Where(Function(t) t.hardware_id = hardware.id).ToList.ForEach(Sub(t) Tags.Remove(t) End Sub) End Sub) Return MyBase.SaveChanges() End Function |
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