Compiled DataContext Query Task with .NET 4

My project (asp.mvc UI layer) was developed using .NET 3.5. After upgrading to .NET 4.0, I had a problem with compiled queries:

[ArgumentException: Query was compiled for a different mapping source than the one associated with the specified DataContext.] System.Data.Linq.CompiledQuery.ExecuteQuery(DataContext context, Object[] args) +863348 System.Data.Linq.CompiledQuery.Invoke(TArg0 arg0, TArg1 arg1) +110 

Every time I run my request, I pass in my context

 return StaticQueries.getTopFiveOrders(mContext, int howMany); public static Func<Mycontext, int, IQueryable<Order>> getTopFiveOrders = CompiledQuery.Compile ((Mycontext mContext, int howMany) => ( some query).Distinct()); 

The error occurs in the second request.

+6
linq-to-sql datacontext
source share
3 answers

This is due to a change in the way compiled queries work.

Now they should always be launched using the same context.

This Microsoft Connect page explains why the change was made:

The problem in this case is caused by the fact that CompiledQuery requires that the same matching source be used for all executions. In the example code that you use to reproduce the problem, different instances of the DataContext using a new matching source each time, but the request does not report this and is simply silent. If you use the DataContext.Log property or other logging, such as SQL Server Profiler, you will see that the second UPDATE is not even sent to the server.

This has been fixed in the .NET Framework 4.0, so an exception is reported that will contain a message like "The request was compiled for a different mapping source than the one associated with the specified DataContext.", And it will not just silently fail. However, the code you provided that works is the right way to do this, because it uses the same static mapping source for all instances of LinqTestDataContext.

In principle, this was always a problem, but was used to refuse silence, they simply made the error explicit in .NET 4.

+4
source share

I spent a lot of time on this and how the behavior has changed in .NET 4.0. I have detailed my findings on my blog here:

http://www.roushtech.net/2014/01/19/statically-compiled-linq-queries-broken-in-net-4-0/

Roughly this: Microsoft made changes to protect people from doing something dumb (reusing a compiled request between different mappings), but it seemed to violate an important performance advantage (reusing a compiled request between different SAME MAPPING contexts, but different display instances )

Using getters or CompiledQuery, which is a member of your class, will result in constant recompilation and will not lead to real performance.

+1
source share

I also ran into a similar problem. I deleted the static file from compiled requests, it works fine. Although I have yet to find out what the difference is in performance.

0
source share

All Articles