嵌套的SqlConnection.Open在TransactionScope中抛出异常

时间:2014-05-28 13:51:30

标签: c# ado.net transactionscope

我在我的存储库单元测试中使用TransactionScope来回滚测试所做的任何更改。

测试的设置和拆卸程序如下所示:

[TestFixture]
public class DeviceRepositoryTests {
    private static readonly string ConnectionString =
        ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;

    private TransactionScope transaction;
    private DeviceRepository repository;

    [SetUp]
    public void SetUp() {
        transaction = new TransactionScope(TransactionScopeOption.Required);
        repository = new DeviceRepository(ConnectionString);
    }

    [TearDown]
    public void TearDown() {
        transaction.Dispose();
    }
}

有问题的测试包括将记录插入数据库的代码和用于检索这些记录的CUT。

    [Test]
    public async void GetAll_DeviceHasSensors_ReturnsDevicesWithSensors() {
        int device1Id = AddDevice();
        AddSensor();

        var devices = await repository.GetAllAsync();

        // Asserts
    }

AddDeviceAddSensor方法打开sql连接并在数据库中插入一行:

    private int AddDevice() {
        var sqlString = "<SQL>";
        using (var connection = CreateConnection()) 
        using (var command = new SqlCommand(sqlString, connection)) {
            var insertedId = command.ExecuteScalar();
            Assert.AreNotEqual(0, insertedId);
            return (int) insertedId;
        }
    }

    private void AddSensor() {
        const string sqlString = "<SQL>";
        using (var connection = CreateConnection()) 
        using (var command = new SqlCommand(sqlString, connection)) {
            var rowsAffected = command.ExecuteNonQuery();
            Assert.AreEqual(1, rowsAffected);
        }
    }

    private SqlConnection CreateConnection() {
        var result = new SqlConnection(ConnectionString);
        result.Open();
        return result;
    }

GetAllAsync方法打开一个连接,执行查询,并为每个获取的行打开新连接以获取子对象。

public class DeviceRepository {
    private readonly string connectionString;

    public DeviceRepository(string connectionString) {
        this.connectionString = connectionString;
    }

    public async Task<List<Device>> GetAllAsync() {
        var result = new List<Device>();
        const string sql = "<SQL>";

        using (var connection = await CreateConnection())
        using (var command = GetCommand(sql, connection, null))
        using (var reader = await command.ExecuteReaderAsync()) {
            while (await reader.ReadAsync()) {
                var device = new Device {
                    Id = reader.GetInt32(reader.GetOrdinal("id"))
                };

                device.Sensors = await GetSensors(device.Id);

                result.Add(device);
            }
        }

        return result;
    }

    private async Task<List<Sensor>> GetSensors(int deviceId) {
        var result = new List<Sensor>();
        const string sql = "<SQL>";

        using (var connection = await CreateConnection()) 
        using (var command = GetCommand(sql, connection, null))
        using (var reader = await command.ExecuteReaderAsync()) {
            while (await reader.ReadAsync()) {
                // Fetch row and add object to result
            }
        }

        return result;
    }

    private async Task<SqlConnection> CreateConnection() {
        var connection = new SqlConnection(connectionString);
        await connection.OpenAsync();
        return connection;
    }
}

问题是当GetSensors方法调用SqlConnection.Open时,我会遇到以下异常:

System.Transactions.TransactionAbortedException : The transaction has aborted.
  ----> System.Transactions.TransactionPromotionException : Failure while attempting to promote transaction.
  ----> System.Data.SqlClient.SqlException : There is already an open DataReader associated with this Command which must be closed first.
  ----> System.ComponentModel.Win32Exception : The wait operation timed out

我可以移动从第一个连接范围中取出子对象的代码(这会起作用),但是让我说我​​不想这样做。

此异常是否意味着无法在单个TransactionScope内打开与DB的同时连接?

修改

GetCommand只需调用SqlCommand构造函数并进行一些日志记录。

private static SqlCommand GetCommand(string sql, SqlConnection connection, SqlParameter[] parameters) {
    LogSql(sql);
    var command = new SqlCommand(sql, connection);

    if (parameters != null)
        command.Parameters.AddRange(parameters);

    return command;
}

1 个答案:

答案 0 :(得分:0)

问题是两个DataReader对象无法同时打开数据库(除非启用了MARS)。这种限制是设计的。在我看来,你有几个选择:

  1. 在您的连接字符串上启用MARS;添加此MultipleActiveResultSets=True
  2. 如果没有必要,请不要使用DataReader。但是你编写代码的方式非常必要。
  3. 在加载设备后填充Sensor属性
  4. 使用Dapper,它可以完成所有这些工作(包括填充Sensor)并且可能更快。
  5. 使用Dapper你可以做这样的事情(你不需要GetSensors):

    public async Task<List<Device>> GetAllAsync() {
        var result = new List<Device>();
        const string sql = "<SQL>";
    
        using (var connection = await CreateConnection())
        using (var multi = connection.QueryMultiple(sql, parms)) {
            result = multi.Read<Device>().ToList();
            var sensors = multi.Read<Sensors>().ToList();
    
            result.ForEach(device => device.Sensors =
                sensors.Where(s => s.DeviceId = device.Id).ToList());
        }
    
        return result;
    }
    

    此处sql看起来像这样:

    SELECT * FROM Devices
    SELECT * FROM Sensors
    

    请参阅Multi Mapping documentation了解Dapper。