[英]How use Transaction with more than functions using c#
如何使用具有多个函数的事务使用 c# 例如我有三个函数
//first function
save();//------to save data-----
//second function
saveDetailes(); //-----to save detiales ----------
//third function
updateStauts(); //--------to update onother table ---------------
我想确保所有这些都使用 TransAction 实现或不实现,谢谢
经过大量尝试和搜索大量资源后,我找到了解决问题的方法
解决方案通过将 sqlcommand 传递给所有函数并从每个函数返回作为 aboolean 值保存完成返回 true 如果三个函数返回 true 事务提交其他方式事务回滚谢谢
如果我理解正确,您需要在多种方法中使用通用的 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;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.