问题描述
我使用实体框架6在MVC 5项目。当你意识到,在SQL Server SELECT
查询执行,如果我们用更快,更高效 WITH(NOLOCK)
在其中。我检查了由实体框架6产生的一些SQL SELECT语句,并意识到他们没有包含NOLOCK。我不想用我的读取操作的事务由未提交的事务读取。 如何执行EF 6使用NOLOCK在下面生成的SELECT语句
?您的意见是很大的AP preciated。谢谢你。
I am using Entity Framework 6 in an MVC 5 project. As you're aware of, SELECT
queries in SQL Server perform faster and more efficient if we use WITH (NOLOCK)
in them. I checked out a few SQL SELECT statements generated by Entity Framework 6 and realized that none of them contain NOLOCK. I do not want to use transactions in my fetch operations to read from uncommitted transactions. How can I enforce EF 6 to use NOLOCK in the underneath generated SELECT statements
? Your feedback is greatly appreciated. Thanks.
推荐答案
首先...你永远也不会使用NOLOCK为每一个SQL语句。这可能危及您的数据的完整性。
First of all... You should NEVER EVER use NOLOCK for each and every SQL Statement. It could compromise the integrity of your data.
这就像任何其他的查询提示,你应该当你做一些与众不同只使用一种机制。
It’s like any other query hint a mechanism you should only use when you do something out of the ordinary.
有没有办法告诉EF提供渲染NOLOCK提示。如果你真的很需要你有以下选项读取未提交的数据。
There is no way to tell the EF Provider to render the NoLock hint. If you really need to read uncommitted data you have the following option.
-
编写您自己的EntityFramework提供商。
Write your own EntityFramework Provider.
使用命令拦截器来修改语句是前执行。 http://msdn.microsoft.com/en-us/data/dn469464.aspx
Use a Command Interceptor to modify the statement before it isexecuted. http://msdn.microsoft.com/en-us/data/dn469464.aspx
使用与IsolationLevel.ReadUncommited一个TransactionScope。
Use a TransactionScope with IsolationLevel.ReadUncommited.
我知道你说你不想使用事务,但它是唯一外的箱子方式读取未提交的数据。同时也不会产生太大的开销,因为SQL Server中的每个语句隐含在一个事务中运行。
I know you said you do not want to use Transactions but it's the only out-of-the box way to read uncommitted data. Also it does not produce much overhead as each statement in SQL Server "implicitly" runs in a transaction.
using (new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadUncommitted
}))
{
using (var db = new MyDbContext()) {
// query
}
}
这篇关于获取实体框架6使用NOLOCK在其下面的SELECT语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!