0

I have a table called devices in my database, EF created a model of that table in my project. I have a list of string called elements, I need loop async thru this elements and do my check and then base on result update the properties of devices object, begining of each iteration i create fresh instance of devices model, after preparing devices object I need to query my devices table in my database to have all records of same element and then update all of them base on new object. when I try to query my devices table in my database I recive this exception

System.InvalidOperationException: '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.'

here is my code flow

static async void Begin(List<string> elements)
{
ParalelForEach(elements, element => {

devices devObj = new devices();
//here i do my operation on element and update devObj object
// now in below i should query my device table in my database to collect all records of same element so I can update them based on new devObj i created but above Exception thrown

var dbElementsList = dbContext.devices.Where(e =>e.name == element).Tolist();//Exception is thrown here

foreach(var dbe in dbElementsList)
{
//update process happens here on dbe
}
dbContext.devices.Add(devObj);
dbContext.SaveChanges();

}):
}
  • Answers to this question might be useful to you: https://stackoverflow.com/questions/12827599/parallel-doesnt-work-with-entity-framework – Gus Jan 02 '19 at 20:26

1 Answers1

2

DbContext is not thread-safe. It uses a single connection to the database, and you shouldn't access a single connection instance from multiple threads (there are exceptions for special types of connections, but better assume you should not and you must not).

To parallelize calls to the db, you need to create a new DbContext instance in the body of Parallel.ForEach.

Nick
  • 4,787
  • 2
  • 18
  • 24
  • would u plz elaborate it more? @Nick – SomeBody Jan 02 '19 at 20:27
  • 2
    Caveat: if the collection is large, a new DbContext for each execution thread probably won't scale well, and will probably still run into table locks in the database. – Gus Jan 02 '19 at 20:29
  • because it throws another error same place "the target principal name is incorrect. Cannot generate SSPI context." – SomeBody Jan 02 '19 at 20:30