How to use WITH(NOLOCK) in LINQ to SQL?

断了今生、忘了曾经 提交于 2019-12-03 22:53:36

问题


we can use SQL just like this:

SELECT * FROM student WITH(NOLOCK);

How can I achieve this with LINQ to SQL without the use of a TransactionScope?


回答1:


LINQ to SQL does not have any mechanism of doing this, but you can create a transaction with a specific isolation level. Look at the code below:

using (var con = new SqlConnection("constr"))
{
    con.Open();

    using (var transaction = con.BeginTransaction(
        IsolationLevel.ReadUncommitted))
    {
        using (var context = new SchoolDataContext(con))
        {
            // HACK: Setting the context.Transaction is 
            // needed in .NET 3.5 (fixed in .NET 4.0).
            context.Transaction = transaction;
            var q = from s in context.Students select c;
        }
    }
}

Sometimes using this type of isolation is useful, i.e. for performance reasons. But please make sure you don't do any create, update or delete (CUD) operations using this type of database isolation. It of course depends on your situations, but your data could get in an inconsistent state.



来源:https://stackoverflow.com/questions/2220769/how-to-use-withnolock-in-linq-to-sql

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