C# 如何使用c使用不止一个函数的事务#
如何使用c使用不止一个函数的事务# 例如 我有三个功能C# 如何使用c使用不止一个函数的事务#,c#,transactions,C#,Transactions,如何使用c使用不止一个函数的事务# 例如 我有三个功能 //first function save();//------to save data----- //second function saveDetailes(); //-----to save detiales ---------- //third function updateStauts(); //--------to update onother table --------------- 我希望确保所有这些都是使用事务实
//first function
save();//------to save data-----
//second function
saveDetailes(); //-----to save detiales ----------
//third function
updateStauts(); //--------to update onother table ---------------
我希望确保所有这些都是使用事务实现的或不是使用事务实现的
谢谢经过多次尝试和搜索,我找到了解决问题的方法 解决方案由 将sqlcommand传递给所有函数,并从每个函数返回一个值save done,返回true 如果三个函数返回true 事务将以其他方式提交事务roolback
谢谢如果我理解正确,您需要在多种方法中使用公共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;
}
}
}
}
这里我们需要更多的细节……您需要什么详细信息?如何将Transaction与三个函数一起使用,并将其移植到一起?这些方法似乎将一些数据保存到数据库中。我们需要知道您是否正在使用ado.net、EF或其他ORM。我们需要知道这些方法是否使用存储过程或内联sql(事实上,如果这实际上是一个关系数据库或NoSql数据库)-您给我们的只是如何调用这些方法-这还不足以开始描述问题,更不用说解决问题了。使用ado.net和使用sqlinside visual stideo