1

I have many deadlock in my application (asp.net mvc , entity framework code first)

so I found some blog posts regarding deadlocks. In one blog post here is suggested to use

 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

dbcontext.database.executesqlcommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;")

I execute this sql command on sql server and then checked the transaction isolation level which was read uncommitted.

but when i run it through code using ef and linq and setting a breakpoints after the line that run "set transaction" and going back to sql to check trnasaction level it still is read committed and again i have so many deadblock.

Another solution that i found is here which suggest to use scope to set isolation level

using (var scope = new TransactionScope(TransactionScopeOption.Required, new 
      TransactionOptions { IsolationLevel= IsolationLevel.Snapshot }))
    {

    // do something with EF here
    scope.Complete();
    }

but is it possible to use scope when using per request context?

The first question is why transaction level is still read committed after setting it to read uncommitted through dbcontext?

the second question is that in this blog post it has mentioned that setting isolation level is per context does this mean that after disposing of dbcontext isolation level goes back to read committed?

and last i'm using ef code first v6 and have used unity to make dbcontext per request what other options i have so i avoid so many deadblock that are happening?

Amir Jalali
  • 3,132
  • 4
  • 33
  • 46

1 Answers1

2

First, check where your deadlocks are coming from. That will help you find your problem areas - the areas you need to fix.

Sometimes ORMs have issues with complex logic. One option is to provide Entity Framework with a stored procedure for reading and writing to your more data-intensive tables.

In your controller or repository layer, you can execute a stored procedure like this:

Context.Database.SqlQuery<MyEntityType>("Exec mySpName \@p0, \@p1", param1, param2);

You can also use Database.ExecuteSqlCommand for procedures that do not return data.

Stored procedures normally have performance gains from execution plan caching.

Using Read Uncommitted is not a magic bullet, but if you really don't care about dirty reads potentially returning bad data, then you can guarantee that your stored procedure will not take read locks by setting the serialization or using the NoLock hint.

Community
  • 1
  • 1
Mike
  • 3,641
  • 3
  • 29
  • 39