DataContext使用.NET 4编译查询问题

mar*_*inn 6 datacontext .net-4.0 linq.compiledquery linq-to-sql

我的项目(UI层是asp.mvc)是使用.NET 3.5开发的.升级到.NET 4.0后,我遇到了编译查询的问题:

 [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
Run Code Online (Sandbox Code Playgroud)

每当我运行我的查询时,我都会传递我的上下文

return StaticQueries.getTopFiveOrders(mContext, int howMany);


public static Func<Mycontext, int, IQueryable<Order>> getTopFiveOrders
            = CompiledQuery.Compile
                ((Mycontext mContext, int howMany) =>
                 ( some query).Distinct());
Run Code Online (Sandbox Code Playgroud)

第二个请求发生错误.

Chr*_*isF 4

这是由于编译查询的操作方式发生了变化。

它们现在需要始终使用相同的上下文运行。

此 Microsoft connect 页面解释了进行更改的原因:

本例中的问题是由于 CompiledQuery 要求所有执行使用相同的映射源而引起的。在您用来重现问题的代码示例中,DataContext 的不同实例每次都使用新的映射源,但查询无法报告此情况,并且只是默默地失败。如果您使用 DataContext.Log 属性或其他日志记录(例如 SQL Server Profiler),您将看到第二个 UPDATE 甚至没有发送到服务器。

此问题已在 .NET Framework 4.0 中修复,因此报告的异常将包含一条消息,例如“查询是为与指定 DataContext 关联的映射源不同的映射源编译的。”,并且它不会只是默默地失败。但是,您提供的有效代码是执行此操作的正确方法,因为它对 LinqTestDataContext 的所有实例使用相同的静态映射源。

基本上,这始终是一个问题,但过去常常默默地失败,他们只是在 .NET 4 中明确地指出了失败。