Skip to content
Advertisement

Delete all related rows to user using EF .NET CORE

I have little problem with data delete. Let s assume that I have to delete user and all related rows to this user. I wrote some code in c#, but it takes ages to complete. Here is my some of my code. My question is how to delete all related data to user the fastest solution. I thought about some trigger on database, is it good ?

Advertisement

Answer

You rely on CascadeOnDelete when deleting your Users. This is a relatively slow process, because for every user that is to be deleted, your database management system will have to check all related tables to see if there is a relation with the user that is to be deleted.

It is way faster to first delete the related objects and then delete the customer:

The problem with Entity Framework is, that you need to fetch the items before you can remove them.

If you need to remove users often, then you can bypass this fetching by creating a stored procedure.

Usage:

Careful: because the procedure is executed immediately you can’t go back once you’ve called the method. If you want a fallback, for instance, you get an exception when removing Groups after the Roles are removed, use DbContext.Database.BeginTranscation / EndTransaction, to get back to the original situation.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement