How to use SQL Server table hints while using LINQ?

自作多情 提交于 2019-12-23 04:09:07

问题


What is the way to use Sql Server's table hints like "NOLOCK" while using LINQ?

For example I can write "SELECT * from employee(NOLOCK)" in SQL.

How can we write the same using LINQ?


回答1:


Here's how you can apply NOLOCK: http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx

(Quote for posterity, all rights reserved by mr scott):

ProductsNewViewData viewData = new ProductsNewViewData();
using (var t = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { 
        IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted 
    }))
{
   viewData.Suppliers = northwind.Suppliers.ToList();
   viewData.Categories = northwind.Categories.ToList();
}



回答2:


I STRONGLY recommend reading about SQL Server transaction isolation modes before using ReadUncommitted. Here's a very good read

http://blogs.msdn.com/b/davidlean/archive/2009/04/06/sql-server-nolock-hint-other-poor-ideas.aspx

In many cases level ReadSnapshot should suffice. Also you if You really need it You can set default transaction isolation level for Your database by using

Set Transaction Isolation Level --levelHere

Other good ideas include packaging Your context in a wrapper that encapsulates each call using demanded isolation level. (maybe You need nolock 95% of the time and serializable 5% of the time). It can be done using using extension methods, or normal methods by code like:

viewData.Categories = northwind.Categories.AsReadCommited().ToList();

Which takes your IQueryable and does the trick mentioned by Rob.

Hope it helps Luke



来源:https://stackoverflow.com/questions/4104323/how-to-use-sql-server-table-hints-while-using-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!