Question

Assume we have a List of entities to be removed:

var items = this.itemRepository.GetRange(1, 1000).ToList();

Instead of simple loop to delete items, I want to remove them concurrently like this:

items.AsParallel().ForAll(item =>
        {
            this.itemRepository.Remove(item);
        });
this.UnitOfWork.Commit();

How do you suggest me to perform delete like this?

Was it helpful?

Solution

The EF context is not thread safe, so I wouldn't do this.

If you need performance then parallel != faster. Parallel code allows you to do more at the same time, but you tend to find that a single unit of work takes at least the same amount of time, but sometimes longer due to context switching etc, it's just that instead of doing 5 things one at a time, you are doing 5 things 5 at a time. This gets you more effective use of available hardware, and is less about performance and more about scalability and responsiveness.


As of EF 6 it exposes an asynchronous API for async/await support, but this again only allows one "concurrent" action against it. If you want to do multiple asynchronous reads, you will need one context per read action - this then simply puts the onus on the database to manage integrity.

OTHER TIPS

EF6 added a RemoveRange method to the DbSet

This is more efficient than removing a single object at a time because by default Entity Framework calls DetectChanges in the Remove method whereas RemoveRange calls it just once.

However, when you call SaveChanges EF still executes individual delete statements. There is a proposal to Batch CUD in a future version.

References:

Entity Framework 6: The Ninja Edition

RemoveRange - implemented in EF6. (with a bug fixed in 6.1)

Upgrade to EF6 if you are not already using it, then you can do the following:

this.itemRepository.RemoveRange(items);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top