Blog on software engineering
How to bulk delete data based on strings in a generic list in C# and EF 4.2

How to bulk delete data based on strings in a generic list in C# and EF 4.2

Let’s assume you have a table Customer in a Microsoft SQL Server database:




And want to delete Customer_008, Customer_009, Customer_010, Customer_011 based on a generic list in C#, you can join this generic list with a entity dbset in entityframework 4.2:

NOTE: For best performance start the query with the generic list and then join on the Customer table.


public void RunNewCodeTest()

private void TestBulkDelete()
    // Define customers to delete in a generic list of strings.
    var names = new List<string>();

    using (var entities = new Rvl.NewCode.Model.NewCodeEntities())
        // To improve performance by a factor 1000, set Configuration.AutoDetectChangesEnabled = false.
        entities.Configuration.AutoDetectChangesEnabled = false;

        // Get customers to delete.
        var query = from name in names
                    join customer in entities.Customer on name equals customer.Name
                    select customer;
        List<Customer> customersToDelete = query.ToList();

        // Delete customers from context.
        foreach (Customer customer in customersToDelete)

        // Delete customers from database.



Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.