Two models are connected by a one-to-many relationship, if you delete this very one - it is clear that all many will be deleted, unless you specify WillCascadeOnDelete(false) . But I need an inverse problem so that one will automatically retire when all that depend on it are deleted.
2 answers
It comes to mind to hang some kind of trigger on the database, which will check when removing many to a single element does not refer to anything => crashes next.
You can make JOB, which will check the elements from time to time and remove the " garbage ".
This problem is very organically solved in the framework of DDD . Each dependent entity must generate a corresponding event when it is deleted. At the application level, there must be a handler interested in these events. When receiving such an event, the handler gets from the database the corresponding entity from which everything depends and reduces its number of dependent ones. If the number of dependents is zero, then the handler deletes the main entity. MediatR can be used as a means of sending events. If your database context exists within the scope of the request, then you will also get consistency and transactionality. If not, consistency ultimately. As a disadvantage, a greater amount of code can be noted as compared with the trigger in the database. The main advantage - business logic does not leak into the database.