重构ADO.NET - 的SqlTransaction主场迎战的TransactionScope [英] Refactoring ADO.NET - SqlTransaction vs. TransactionScope
问题描述
我也继承,创建一个ADO.NET SqlCommand对象和遍历的项目清单一点点C#的方法来保存到数据库(SQL Server 2005)。
I have "inherited" a little C# method that creates an ADO.NET SqlCommand object and loops over a list of items to be saved to the database (SQL Server 2005).
现在,传统的SqlConnection / SqlCommand的方法使用,以确保一切正常,这两个步骤(删除旧的条目,然后将新的)被封装到一个ADO.NET的SqlTransaction。
Right now, the traditional SqlConnection/SqlCommand approach is used, and to make sure everything works, the two steps (delete old entries, then insert new ones) are wrapped into an ADO.NET SqlTransaction.
using (SqlConnection _con = new SqlConnection(_connectionString))
{
using (SqlTransaction _tran = _con.BeginTransaction())
{
try
{
SqlCommand _deleteOld = new SqlCommand(......., _con);
_deleteOld.Transaction = _tran;
_deleteOld.Parameters.AddWithValue("@ID", 5);
_con.Open();
_deleteOld.ExecuteNonQuery();
SqlCommand _insertCmd = new SqlCommand(......, _con);
_insertCmd.Transaction = _tran;
// add parameters to _insertCmd
foreach (Item item in listOfItem)
{
_insertCmd.ExecuteNonQuery();
}
_tran.Commit();
_con.Close();
}
catch (Exception ex)
{
// log exception
_tran.Rollback();
throw;
}
}
}
现在,我已经读了很多有关.NET TransactionScope类最近,我在想,什么是preferred的做法吗?我会通过切换到使用获得任何(可读性,速度,可靠性) P>
Now, I've been reading a lot about the .NET TransactionScope class lately, and I was wondering, what's the preferred approach here? Would I gain anything (readibility, speed, reliability) by switching to using
using (TransactionScope _scope = new TransactionScope())
{
using (SqlConnection _con = new SqlConnection(_connectionString))
{
....
}
_scope.Complete();
}
你会怎么preFER,为什么?
What you would prefer, and why?
马克·
推荐答案
您不会立即获得通过转换现有的code使用的TransactionScope
东西。你应该使用的,因为它提供了灵活性以备将来的发展。这将使它更容易在将来包括其他的东西比ADO.NET调用到一个事务。
You won't immediately gain anything by switching your existing code to use TransactionScope
. You should use it for future development because of the flexibility it provides. It will make it easier in the future to include things other than ADO.NET calls into a transaction.
顺便说一句,在你张贴的例子中,的SqlCommand
情况下,应该在使用
块。
BTW, in your posted example, the SqlCommand
instances should be in using
blocks.
这篇关于重构ADO.NET - 的SqlTransaction主场迎战的TransactionScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!