【发布时间】:2015-07-15 04:53:14
【问题描述】:
我正在使用 C# 和 ADO.Net 以及 TransactionScope 在 ASP.Net 应用程序中运行事务。该事务应该跨多个表保存一些数据,然后向订阅者发送电子邮件。
问题:当它包含对在 SQL Server 2014 中具有自己事务的存储过程的调用时,它是否有效使用 TransactionScope,或者我应该删除 SQL 事务语句,即begin tran、commit tran 和 rollback tran 语句来自在此 TransactionScope 中调用的存储过程?
这个场景的C#代码和存储过程的T-SQL代码都在下面提到。
使用TransactionScope的C#代码:
try
{
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection connection1 = new SqlConnection(connectString1))
{
// Opening the connection automatically enlists it in the
// TransactionScope as a lightweight transaction.
connection1.Open();
// SaveEmailData is a stored procedure that has a transaction within it
SqlCommand command1 = new SqlCommand("SaveEmailData", connection1);
command1.CommandType = CommandType.StoredProcedure;
command1.ExecuteNonQuery();
}
//Send Email using the helper method
EmailHelper.SendCustomerEmails(customerIds);
// The Complete method commits the transaction. If an exception has been thrown,
// Complete is not called and the transaction is rolled back.
scope.Complete();
}
}
catch( Exception ex)
{
Logger.Log(ex);
}
存储过程的T-SQL SaveEmailData:
SET NOCOUNT ON
BEGIN TRY
DECLARE @emailToUserId BIGINT
BEGIN TRAN
-- //update statement. detail statement omitted
UPDATE TABLE1...
--update statement. detail statement omitted
UPDATE TABLE2...
IF @@trancount > 0
BEGIN
COMMIT TRAN
END
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
BEGIN
ROLLBACK TRAN
END
EXEC Error_RaiseToADONET
END CATCH
【问题讨论】:
标签: c# sql-server stored-procedures ado.net transactionscope