如何使用WITH(NOLOCK)在LINQ到SQL?如何使用、WITH、NOLOCK、LINQ

2023-09-04 00:35:40 作者:两不相欠

我们可以使用SQL就像这样:

we can use SQL just like this:

SELECT * FROM student WITH(NOLOCK);

我怎样才能做到这一点的LINQ无需使用到SQL中的的TransactionScope

推荐答案

的LINQ to SQL不具备这样做的任何机制,但您可以创建一个交易与特定的隔离级别。看看下面的code:

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;
        }
    }
}

有时候,使用这种隔离是有用的,即对于性能方面的原因。但是,请确保你没有做任何创建,更新或删除使用这种类型的数据库隔离(CUD)操作。这当然要看你的情况,但数据可以得到不一致的状态。

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.