Entity Framework: Using transactions and rollbacks… Possible?

后端 未结 3 1747
天命终不由人
天命终不由人 2020-12-13 15:08

Issue: (With Sql 2005)

  • How can I query the database while the transaction is up? (Since it locks the table)
  • How can cause a t
3条回答
  •  情深已故
    2020-12-13 15:30

    I have been able to solve very similar problem using this code fragment:

    var connection = new EntityConnection("name=MyEntities");
    connection.Open();
    var tran = connection.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted);
    
    try
    {
        var dataContext = new MyEntities(connection);
    
        //CRUD operation1
    
        //CRUD operation2
    
        //CRUD operation3 ...
    
        Assert.AreEqual(expected, actual);
    }
    catch
    {
        throw;
    }
    finally
    {
        tran.Rollback();
        connection.Close();
    }
    

    Where MyEntities is the EF DataModel. The crucial part is the setting of the transaction: System.Data.IsolationLevel.ReadUncommitted.
    Using this isolation level SQL queries can read you changes done inside the transaction. Also you need to explicitly create a connection as I do on the first and second line. I couldn't make it work using TransactionScope unfortunately.

提交回复
热议问题