我有以下使用 SqlTransaction 的代码
string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
int logID = HelperClass.InsertException(connection, 1, DateTime.Now, "Y", "test", "test", 1, 1, transaction);
LogSearch logSearch = new LogSearch();
logSearch.LogID = 258;
Collection<Log> logs = HelperClass.GetLogs(logSearch, connectionString);
}
此代码引发以下异常。
超时已过。在操作完成之前超时时间已过或服务器没有响应。
但是,如果我为 LogID 传递硬编码值,也不例外。
问题
- 为什么当我传递 logID(InsertException() 的结果)时会出现异常?
- 请解释为什么当我将
hard coded
值作为 LogID传递时没有异常
注意:InsertException() 使用一个连接,SqlTransaction
而 GetLogs() 使用一个没有任何事务的新连接
更新的问题
业务层代码不使用Transaction
. 我需要在上面显示的单元测试代码中调用业务层方法(用于集成测试)。即使业务层不使用事务,我们如何将事务应用于 UT 代码(用于集成测试)?从@jbl 的回答看来,在单元测试中根本不可能使用事务。我们如何为 UT 代码申请交易。
代码
public static class HelperClass
{
public static Collection<Log> GetLogs(LogSearch logSearch, string connectionString)
{
Collection<Log> logs = new Collection<Log>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = "SELECT * FROM Application_EX WHERE application_ex_id = @application_ex_id";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
//Parameter value setting
command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
}
}
}
}
}
return logs;
}
public static Int16 InsertException(SqlConnection connection, Int16 applicationID, DateTime createdDate, string isInternalLocationIndicator, string exceptionDescription, string operation, Int16 severityLevelNumber, Int16 exceptionTypeCode, SqlTransaction transaction)
{
Int16 newLogID = 0;
string commandText = @"INSERT INTO Application_Ex
VALUES (@severity_level_nbr, @appl_service_id, @ex_internal_appl_ind,
@application_ex_txt,@ex_location_txt,@create_ts,@application_ex_code);
SELECT SCOPE_IDENTITY() AS [LogIdentity];";
using (SqlCommand command = new SqlCommand(commandText, connection, transaction))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@severity_level_nbr", severityLevelNumber);
command.Parameters.AddWithValue("@appl_service_id", applicationID);
command.Parameters.AddWithValue("@ex_internal_appl_ind", isInternalLocationIndicator);
command.Parameters.AddWithValue("@application_ex_txt", exceptionDescription);
command.Parameters.AddWithValue("@ex_location_txt", operation);
command.Parameters.AddWithValue("@create_ts", createdDate);
command.Parameters.AddWithValue("@application_ex_code", exceptionTypeCode);
newLogID = Convert.ToInt16(command.ExecuteScalar(), CultureInfo.InvariantCulture);
}
return newLogID;
}
}