Anup
Anup

Reputation: 9738

How to roll back queries in C#?

I have list of delete queries & I execute them with this code:

using (var ctx = new ApplicationDbContext(schemaName))
{
    foreach (var item in queries)
    {
        ctx.Database.ExecuteSqlCommand(item);
    }
}

I want to commit all the delete queries, but I want to roll back if there is some error in any of the queries.

How to do roll back in the above scenario?

Upvotes: 1

Views: 77

Answers (1)

Dawid Wekwejt
Dawid Wekwejt

Reputation: 543

Try to use TransactionScope

using System.Transactions;

try
{
    using (var scope = new TransactionScope())
    {
        using (var ctx = new ApplicationDbContext(schemaName))
        {
            foreach (var item in queries)
            {
                ctx.Database.ExecuteSqlCommand(item);
            }
        }
        scope.Complete();
    }
}
catch (Exception ex)
{

}

Upvotes: 3

Related Questions