我在我的存储库单元测试中使用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
}
AddDevice
和AddSensor
方法打开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;
}
答案 0 :(得分:0)
问题是两个DataReader
对象无法同时打开数据库(除非启用了MARS
)。这种限制是设计的。在我看来,你有几个选择:
MARS
;添加此MultipleActiveResultSets=True
DataReader
。但是你编写代码的方式非常必要。Sensor
属性。Sensor
)并且可能更快。使用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。