Search code examples
c#sql-serverlinqsubmitchanges

Does deleting from a LINQ DB also delete records in other tables that have a foreign key association?


So at the root of my DB, I have a table "Customer." Customer has foreign keys going to about 6-7 other tables such as Receipts, Addresses, Documents etc. If I were to delete a customer using SubmitChanges(), would that seek out all those records with the foreign key association and delete them too, or would I need to do like 6 queries?


Solution

  • This will only happen if you have set up your database tables to do this with cascading deletions (i.e. on delete cascade).

    For more information please see Insert, Update, and Delete Operations (LINQ to SQL):

    LINQ to SQL does not support or recognize cascade-delete operations. If you want to delete a row in a table that has constraints against it, you must either set the ON DELETE CASCADE rule in the foreign-key constraint in the database, or use your own code to first delete the child objects that prevent the parent object from being deleted. Otherwise, an exception is thrown.