0 Comments

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

 

image

 

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.

 

[TestMethod]
public void RunNewCodeTest()
{
    TestBulkDelete();
}

private void TestBulkDelete()
{
    // Define customers to delete in a generic list of strings.
    var names = new List<string>();
    names.Add("Customer_038");
    names.Add("Customer_039");
    names.Add("Customer_040");
    names.Add("Customer_041");

    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)
        {
            entities.Customer.Remove(customer);
        }

        // Delete customers from database.
        entities.SaveChanges();
    }
}

 

 


        
                

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Related Posts