我在TransactionScope中的SQL服务器中进行一些插入操作。
这是我的代码
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
Int32 existingDBRowCount = GetTableRowCount(currentTableName);
//... Code to Insert Data into Table
Int32 newDBRowCount = GetTableRowCount(currentTableName);
// New Row Count should be equal to Existing DB Row Count + Rows to be inserted
if (newDBRowCount != (existingDBRowCount + toBeInsertedRowCount))
Transaction.Current.Rollback();
else
scope.Complete(); // Commit the Transaction
}
public Int32 GetTableRowCount(string tableName)
{
using (SqlConnection sqlConnection = GetSQLConnection())
{
if (sqlConnection.State != ConnectionState.Open)
sqlConnection.Open();
string queryString = "SELECT COUNT(*) FROM [" + tableName + "]";
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = queryString;
var rowCount = (int) sqlCommand.ExecuteScalar();
return rowCount;
}
}
}
基本上我正在做的是我跟踪表中的行数,然后在插入新数据后,检查新行数=现有行数+要插入的行数
如果两者匹配,我提交事务,否则回滚
我有两个问题:
1)这个apprach是否正确?
2)在某些情况下,新的DB Row Counts与现有的行相同,我认为这是因为我的事务在此之前尚未提交,但它非常随机,大多数情况下返回正确的行数。我无法弄清楚什么是错的
答案 0 :(得分:1)
如果您想要正确的行数,即使没有提交数据,您还需要在读取表行计数时设置IsolationLevel.ReadUncommitted
SqlTransaction transaction = SqlConnection.BeginTransaction(IsolationLevel.ReadUncommitted);
然后将此事务分配给SQL命令
请参阅此链接http://msdn.microsoft.com/en-us/library/5ha4240h(v=vs.110).aspx