I am inserting values into two tables using two stored procedure , and the data in both tables are linked to each other so i want if any error occurs in second stored procedure ,the data entered via 1st stored procedure should get roll backed.
I am using Sql server 2008 as my back end and ASP.net (c#) as front end
use need to use TransactionScope
as below
using(var tran = new TransactionScope())
{
//calling stored procedures here
tran.Complete();
}
when an exception occurs the control will go out from the using and thus transaction
will rollback
if you are using entity framework you can use it.
using (var dataContext = new SchoolMSDbContext())
{
using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
{
try
{
// your query
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
Console.WriteLine(ex.InnerException);
}
}
}
Or you can try this
using (var dataContext = new SchoolMSDbContext())
{
using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
//your query
transaction.Complete();
}
catch (Exception ex)
{
transaction.Dispose();
Console.WriteLine(ex.InnerException);
}
}
}
for this you'll have to this references.
System.Transactions
for more information check this links https://msdn.microsoft.com/en-us/data/dn456843.aspx https://msdn.microsoft.com/en-us/library/2k2hy99x(v=vs.110).aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.