ADO.Net Entity Framework : (二) 實現 with(nolock) 查詢

来源:互联网 发布:淘宝奇葩评价 编辑:程序博客网 时间:2024/03/29 23:43

因為公司的案子在執行資料查詢時,都習慣在查詢語法裡使用With(nolock), 
用以提升查詢效率與避免LOCK發生,如下

1select from [Userwith(nolock)

剛好之前在使用Entity Framework時,也有這個需求, 
因此找了一下資料
要在 Linq to SQL 或 Entity Framework 下實現 with(nolock) 查詢方法如下 

方法一   使用 TransactionScope

01////示範: with(nolock)查詢
02using (TestEntities te = new TestEntities())
03{
04    ////方法一
05    ////須引用 System.Transactions
06    using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required
07        new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted }))
08    {
09        var users = te.User.Select(a => a).ToList();
10    }
11}

需注意此方法在跨資料庫查詢時,啟動MSDTC,並降低效能。

 

方法二  使用 ObjectContext.Connection.BeginTransaction

view source
print?
1////示範: with(nolock)查詢
2using (TestEntities te = new TestEntities())
3{
4    ////方法二
5    ////此方法會修改所有操作的交易層級
6    te.Connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
7    var users = te.User.Select(a => a).ToList();
8}

需注意此方法會修改所有操作的交易層級

 

方法三  使用預存程序(stored procedures ),將查詢語法包裝在裡面

 

提供一些心得給大家參考