如何将事务与使用c#的函数一起使用 例如 我有三个功能
//first function
save();//------to save data-----
//second function
saveDetailes(); //-----to save detiales ----------
//third function
updateStauts(); //--------to update onother table ---------------
我想确保使用TransAction实现或不实现所有这些 谢谢
答案 0 :(得分:0)
经过多次尝试和搜索,我找到了解决我问题的方法
解决方案 将sqlcommand传递给所有函数并从每个函数返回,因为布尔值已保存完成返回true 如果三个函数返回true 事务以其他方式提交事务回滚 谢谢
答案 1 :(得分:0)
如果我正确理解它,则需要在多种方法中使用通用的SqlTransaction。这就是我的方法。首先,您必须将所有方法收集到一个通用方法中。然后,将您的SqlConenction和SqlTransaction传递给所有方法,并返回一个布尔标志,以通知您的主方法您的查询是否成功。
using System.Data.SqlClient;
namespace SqlTransationDemo
{
class Program
{
static void Main(string[] args)
{
//Do your sql logic here
DoSomething();
}
private static bool DoSomething()
{
try
{
using (var connection = new SqlConnection("SqlConnectionString"))
{
connection.Open();
//If not commited, transaction is rolled-back as soon as it is disposed
using (var transaction = connection.BeginTransaction())
{
//Either use a false loop to break or throw an exception. Your choice.
do
{
if (!Foo1(connection, transaction))
break;
if (!Foo2(connection, transaction))
break;
if (!Foo3(connection, transaction))
break;
//Commit
transaction.Commit();
return true;
}
while (false);
}
}
}
catch
{
return false;
}
}
private static bool Foo1(SqlConnection Connection, SqlTransaction Transaction)
{
try
{
using (var command = new SqlCommand())
{
command.Connection = Connection;
command.Transaction = Transaction;
command.CommandText = "Query1";
command.ExecuteNonQuery();
}
return true;
}
catch
{
return false;
}
}
private static bool Foo2(SqlConnection Connection, SqlTransaction Transaction)
{
try
{
using (var command = new SqlCommand())
{
command.Connection = Connection;
command.Transaction = Transaction;
command.CommandText = "Query2";
command.ExecuteNonQuery();
}
return true;
}
catch
{
return false;
}
}
private static bool Foo3(SqlConnection Connection, SqlTransaction Transaction)
{
try
{
using (var command = new SqlCommand())
{
command.Connection = Connection;
command.Transaction = Transaction;
command.CommandText = "Query3";
command.ExecuteNonQuery();
}
return true;
}
catch
{
return false;
}
}
}
}