I’m using Linq to SQL to access my database. I want to have a ‘delete account’ feature which basically gets rid of all records in all tables that belong to a given user. What would be the most efficient way of doing this?
The deletion has to occur in a certain order, otherwise there are foreign key integrity errors. I can do this manually from the database, and my guess would be to simply emulate that in L2S e.g. (pseudo code)
var tb1del = From Table1 Where userId == userIdToDelete;
mydatacontext.Table1.deleteonsubmit(tb1del);
var tb1de2 = From Table1 Where userId == userIdToDelete;
mydatacontext.Table2.deleteonsubmit(tb1de2);
...
However, I’m sure that’s not the most efficient way of deleting the records.
The simplest solution is just to create a
FOREIGN KEYconstraint withON DELETE CASCADEin the database. That way you don’t need to worry about the deletion order, or anything else. Just delete the account record and you’re done.