在EntityFramework中使用 nock的方法。

以下内容为转载:

A:https://dotblogs.com.tw/asdtey/2009/09/27/10793

B:http://www.gitshah.com/2014/08/how-to-add-nolock-hint-to.html

 

1,方法一   使用 TransactionScope

2,  使用 ObjectContext.Connection.BeginTransaction

  

using (TestEntities te = new TestEntities()) {

////方法二 ////此方法會修改所有操作的交易層級 te.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);

var users = te.User.Select(a => a).ToList();

}

 

3,重写 DbCommandInterceptor

public class NoLockInterceptor : DbCommandInterceptor

{

private static readonly Regex _tableAliasRegex =

new Regex(@"(?<tablealias>AS \[Extent\d+\](?! WITH \(NOLOCK\)))",

RegexOptions.Multiline | RegexOptions.IgnoreCase);

[ThreadStatic]

public static bool ApplyNoLock;

public override void ScalarExecuting(DbCommand command,

DbCommandInterceptionContext<object> interceptionContext)

{

if (ApplyNoLock)

{

command.CommandText =

_tableAliasRegex.Replace(command.CommandText,

"${tableAlias} WITH (NOLOCK)");

}

}

public override void ReaderExecuting(DbCommand command,

DbCommandInterceptionContext<dbdatareader> interceptionContext)

{

if (ApplyNoLock)

{

command.CommandText =

_tableAliasRegex.Replace(command.CommandText,

"${tableAlias} WITH (NOLOCK)");

}

}

}

3.1

NoLockInterceptor.ApplyNoLock = true;

3.2

DbInterception.Add(new NoLockInterceptor());

posted @ 2016-06-22 09:42  张保维  阅读(246)  评论(0编辑  收藏  举报