Multi-Threaded SubQueries Using Entity Framework Throws Errors

I am trying to update the performance of my code regarding database queries. The problem I'm currently facing is that I cannot find a way to get a new context for each subQuery.

Using the simplified code below, you arbitrarily generate an "Invalid base provider upon opening".

using (var context = getNewContextObject()) { var result = new SomeResultObject(); var parentQuery = context.SomeTable.Where(x => x.Name = "asdf"); Parallel.Invoke(() => { result.count1 = parentQuery.Where(x => x.Amount >= 100 & x.Amount < 2000).Count(); }, () => { result.count2 = parentQuery.Where(x => x.Amount < 100).Count(); } , () => { result.count3 = parentQuery.Where(x => x.Amount >= 2000).Count(); } ); } 

The only way it still seems to be to rebuild the entire query for each subQuery with a new context. Is there a way to avoid building each request from the bottom up using the new Context? Can I instead simply attach each subquery request to a new context? I am looking for something like below.

  Parallel.Invoke(() => { var subQuery = parentQuery.Where(x => x.Amount >= 100 & x.Amount < 2000).Count(); subQuery.Context = getNewContextObject(); result.count1 = subQuery.Count(); }, () => { var subQuery = parentQuery.Where(x => x.Amount < 100).Count(); subQuery.Context = getNewContextObject(); result.count2 = subQuery.Count(); } , () => { var subQuery = parentQuery.Where(x => x.Amount >= 2000).Count(); subQuery.Context = getNewContextObject(); result.count3 = subQuery.Count(); } ); } 
+4
source share
1 answer

I'm not sure how this exactly relates to your problem, but none of the EF features are thread safe, so I expect that running multiple requests in the same instance of the context could explode in parallel for any reason. For example, they access the same connection property in the context, but the threads do not know about each other, so they can close the connection to another thread or replace the instance with another instance of the connection (you can try to open the connection manually before starting parallel threads and close it as soon as all threads are executed, but this will not necessarily be the only problem).

+7
source

All Articles