Nolock as default for Create One ObjectContext per Request for EF4

1.1k Views Asked by At

Is there any side effect for this code:


///This code runs per request 
public static MyObjectContext CreateEntity()
{
  MyObjectContext db=new MyObjectContext();

  db.Connection.Open();
  var con = (SqlConnection)((EntityConnection)hi.Connection).StoreConnection;
  SqlCommand cmd = new SqlCommand("set transaction isolation level read uncommitted",con);
  cmd.ExecuteNonQuery();

  return db;
}

Now "db" instance will run ReadUncommited mode?

1

There are 1 best solutions below

4
On

The side effect is that you must handle your connection manually and that the connection is held by the context for whole its lifetime. It is also kept opened for the whole lifetime of the context which can be less efficient.

Another side effect is read uncommited isolation level itself which is quite dangerous to use because it allows reading uncommited transactional data.

Why do you need this? EF by default uses default transaction isolation mode of the database server. For SQL server it is read commited. EF also by default doesn't hold locks on records because each read operation is only part of a transaction with duration just for that read. Only SaveChanges uses transaction for multiple database commands.