Search code examples
c#entity-frameworkado.net

Entity Framework with NOLOCK


How can I use the NOLOCK function on Entity Framework? Is XML the only way to do this?


Solution

  • No, but you can start a transaction and set the isolation level to read uncommited. This essentially does the same as NOLOCK, but instead of doing it on a per table basis, it will do it for everything within the scope of the transaction.

    If that sounds like what you want, here's how you could go about doing it...

    //declare the transaction options
    var transactionOptions = new System.Transactions.TransactionOptions();
    //set it to read uncommited
    transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
    //create the transaction scope, passing our options in
    using (var transactionScope = new System.Transactions.TransactionScope(
        System.Transactions.TransactionScopeOption.Required, 
        transactionOptions)
    )
    
    //declare our context
    using (var context = new MyEntityConnection())
    {
        //any reads we do here will also read uncomitted data
        //...
        //...
        //don't forget to complete the transaction scope
        transactionScope.Complete();
    }