Reputation: 3373
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?
Upvotes: 1
Views: 2038
Reputation: 22595
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)
Upvotes: 1
Reputation: 208
Upgrade to EF6 if you are not already using it, then you can do the following:
this.itemRepository.RemoveRange(items);
Upvotes: 0
Reputation: 64517
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.
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.
Upvotes: 4