.NET 4的DataContext编译查询问题 [英] DataContext compiled query problem with .NET 4

查看:78
本文介绍了.NET 4的DataContext编译查询问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My project (UI layer is asp.mvc) was developed using .NET 3.5. After upgrading to .NET 4.0 I have got 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 when I run my query I am passing 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 on the second request.

推荐答案

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

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

现在它们必须始终使用相同的上下文运行.

They now need to be always run using the same context.

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

This Microsoft connect page explains why the change was made:

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

The problem in this case is caused by the fact that CompiledQuery requires the same mapping source to be used for all executions. In the code example you are using to reproduce the problem, the different instances of the DataContext using a new mapping source every time, but the query fails to report this, and just silently fails. If you use the DataContext.Log property or other logging like SQL Server Profiler, you will see that the second UPDATE is not even being sent to the server.

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

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

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

Basically it was always a problem but used to fail silently, they just made the failure explicit in .NET 4.

这篇关于.NET 4的DataContext编译查询问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆