如何强制重新编译 Linq to SQL 查询的执行计划?
我有一个动态创建的 LINQ to SQL 查询。有趣的是,当我在 SQL Management Studio 中运行它时,速度快如闪电。当我从 L2S 运行它时,一段时间后它变得非常慢。
这可能是由于查询计划/执行计划造成的。当我重新启动 SQL Server 时,L2S 查询也再次变得快如闪电。
现在,通过 T-SQL,您可以使用“WITH RECOMPILE”。但如何使用 L2S 做到这一点呢?
I have a LINQ to SQL query that's created dynamically. Funny thing is, when I run it in SQL Management Studio it's lightning fast. When I run it from L2S it becomes awefully slow after a while.
This is probably because of the query plan/execution plan. When I restart SQL Server the L2S query is also lightning fast again.
Now with T-SQL you can have WITH RECOMPILE. But how to do this with L2S?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如我在下面的线程中发现的,您可以使用
DataContext.GetCommand(IQueryable)
来获取您希望执行的查询的DbCommand
。您可以将“选项(重新编译)”添加到命令文本,然后打开阅读器,然后使用[DataContext.Translate
]1 将打开的阅读器转换为您想要的实体类型。http://social. msdn.microsoft.com/Forums/en-US/linqtosql/thread/def80609-eaf2-4631-8d3d-ad10fc9aedfa
例如,给定一个
DataContext dataContext
:As I found in the thread below, you can use the
DataContext.GetCommand(IQueryable)
to get aDbCommand
for the query you wish to execute. You can add "OPTION (RECOMPILE)" to the command text, from that, open a reader, and use[DataContext.Translate<T>
]1 to translate the opened reader to the entity type you wanted.http://social.msdn.microsoft.com/Forums/en-US/linqtosql/thread/def80609-eaf2-4631-8d3d-ad10fc9aedfa
For example, given a
DataContext dataContext
:从您描述的行为来看,您的统计数据几乎肯定已经过时。
我建议你重建它们:
From the behaviour you describe, your statistics are almost certainly out of date.
I suggest you rebuild them:
查看 CompiledQuery 类。这是来自 Microsoft 的教程,其中甚至介绍了更多细节。
Check out the CompiledQuery class. Here's a tutorial from Microsoft that goes into even more detail.
我使用这个 EF 6 参数嗅探 在 SQL 命令末尾添加“执行前的选项(重新编译)”。它对我有用。这是一个非常好的解决方法。
I used this EF 6 Parameter Sniffing to add at the end of SQL commands "option(recompile)" before executing. It work for me. It is very good workaround how to solve it.