1 year ago

#159132

test-img

Akhil RJ

How to share DbContext between multiple threads

I'm trying to implement a bulk insert and delete operation based on some specifications i.e IList<Specification> provided by the user. The data which needs to be queried is roundabout 1 million, based on which I need to insert or delete records to/from another table i.e UserSpecifications table which have only two columns UserId and SpecificationId and PK is UserId + SpecificationId

Order in which the records get inserted/deleted into UserSpecifications table doesn't matter

Hence I'm trying to create Parallel tasks for each user specification and process data into UserSpecifications

    await Task.Run(() => Parallel.ForEach(specifications, async specification =>
    {
        await insertBulkRecordsAsync(specification); // this uses SqlBulkCopy for data insertion with transaction scope , on 1 million records
        await deleteRecordsAsync(specification); // this uses https://entityframework-plus.net/batch-delete operation
    }));

both insertBulkRecordsAsync & deleteRecordsAsync uses userContext

When I try to run this piece of code I get the following exception

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread-safe.

I know that EF 6 doesn't support sharing dbContext, but if I run a normal forEach loop things do work but it takes a lot of time to process the updates

Following works without any issue

foreach (var specification in specifications)
{
  await insertBulkRecordsAsync(specification);
  await deleteRecordsAsync(specification);
}

So do we have any way to share the context and increase the execution time

c#

entity-framework

entity-framework-6

task-parallel-library

entity-framework-plus

0 Answers

Your Answer

Accepted video resources