Sami
Sami

Reputation: 1389

Change DataContext of IQueryable

I am working on a project that uses a static global DataContext (Which is not recommended but extremely hard to change at this point). I currently need to increase the performance of some parts by parallelizing some functions that are independent. Since DataContext is not thread-safe, I cannot use it inside of the newly created threads. Therefore, I created a new DataContext inside each thread and disposed it at the end of the thread.

Everything goes fine with the new datacontext, but I have a problem that one of the inputs of the function is an IQueryable that is attached to the Global DataContext. Running the method will result an exception of "There is already an open DataReader associated with this Command which must be closed first."

The question is, how would I be able to run the IQueryable with the new data context instead of the changed one.

Kindly find below a sample code for the threads:

var myQueryable = Global.DataContext.Customers.Where(a => a.Age <12);

ParallelLoopResult threads = Parallel.ForEach(groups, group =>
        {
            DataContext ctx = new DataContext(Const.ConnectionString);
            myFunction(myQueryable);
            ctx.Dispose();
        });

The option of re-writing the myQueryable inside of the thread is unfortunately quite difficult as there is a big amount of logic to generate it. Converting it to list and then passing it is also not an option as the query returns thousands of entries and would affect the performance negatively.

Any help is highly appreciated

Upvotes: 4

Views: 1318

Answers (1)

svick
svick

Reputation: 244757

I have not tested this, but I think what could work is to get your queryable with the right Expression, but the wrong Provider and combine it with one which has the right Provider, but the wrong Expression. To do that, use CreateQuery():

var contextQueryable = ctx.Customers.AsQueryable();

var fixedQueryable = contextQueryable.Provider.CreateQuery<Customer>(myQueryable.Expression);

Upvotes: 5

Related Questions