Miguel A. Arilla
Miguel A. Arilla

Reputation: 5334

Insert into DbContext Multithreading

I am getting the following exception when trying to add new entities to DbContext from some tasks, the code worked before adding tasks to the matter.

$exception {"The context cannot be used while the model is being created."} System.Exception {System.InvalidOperationException}

I've done some research and I found this, and it contains some usefull information to my problem:

Another reason for this error can be that while you create the context the first time and therefore cause the model to be created you create another context on a separate thread. You will have to wait for other context instances to be created after the model creation has completed.

So I guess the question is what is the proper way to wait for the context?

Here its my code in case I'm guessing wrong about my problem:

using(SampleEntities context = new SampleEntities())
{
    context.Configuration.LazyLoadingEnabled = false; //I tried this in case it was the problem
    Task[] TaskArray = new Task[4];
    for (int i = 0; i < TaskArray.Length; i++)
        TaskArray[i] = Task.Run(() =>
            {
                SampleEntity Result = null;
                while(this._Data.TryDequeue(out Result)) //where Data is a ConcurrentQueue<SampleEntity> with the entities to insert
                {
                    if(!context.SampleEntity.Any(/*Comparisons between properties to check if the entities values are already inserted*/)
                        context.Add(Result);
                }
            }
    Task.WaitAll(TaskArray);
    context.SaveChanges();
}

The exception is thrown at the line if(!context.SampleEntity.Any(...

EDIT:

I have a large amount of registers previously enqueued in _Data and I was trying to make the mass insert faster if possible.

Upvotes: 0

Views: 1622

Answers (1)

sribin
sribin

Reputation: 1736

One context and many threads - it is a bad practice. It is best to create the context for each thread. I could recommend to you reconsider your algorithm and reate the context for each thread.

Upvotes: 1

Related Questions