سلام
از Transaction به همراه Commit و Rollback استفاده کنید
private void SqlTrans(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// شروع تراکنش.
transaction = connection.BeginTransaction("SampleTransaction");
command.Connection = connection;
command.Transaction = transaction;
//دو عملیات درج همزمان
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
transaction.Commit();
هر دو رکورد توی دیتابیس در اینجا ثبت میشه
}
catch (Exception ex)
{
try
{
transaction.Rollback();
اگر اتفاقی بد بیوفته هد دو عمل درج کنسل میشه
}
catch (Exception ex2)
{
}
}
}
}