Linq to SQL delete multiple/bulk records (batch delete)

Normally when building ASP.NET applications Linq to SQL makes the job a whole lot easier. It takes care of all the data access for creating, updating and deleting individual records. However every so often I come across the need to delete multiple records such as the case with a one to many relationship, where I need to delete all related records for a specific group. Unfortunately this is not as simple as you would think using Linq to SQL as Linq to SQL only deals with one record at a time. For a large high performance application where large numbers of records need to be deleted the best approach would be to use a stored procedure. In some cases the delete is contained to small datasets and would not be used frequently so keeping all of your code in Linq to SQL keeps it clean and consistent. In this case I have found the sample code below does the trick.

MyAppDataContext db = new MyAppDataContext();

var deleteRelatedRecords =
from relatedRecords in db.RelatedRecords
where relatedRecords.MyForeignKeyID == MyPrimaryKeyID
select relatedRecords;

foreach (var relatedRecords in deleteRelatedRecords)


This code works well if all you need to do is clean up/delete a small group of records, it first gets the group of records, then loops through the dataset flagging each one to be deleted. Once completed the changes are submitted committing the deletes.

Additional information and samples in other languages can be found here