1

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Anup
  • 9,396
  • 16
  • 74
  • 138
  • Related/possible dup: [Entity Framework 6 transaction rollback](http://stackoverflow.com/questions/22486489/entity-framework-6-transaction-rollback) – crashmstr Dec 28 '16 at 12:56
  • The keyword you may be looking for is "Transaction". I've linked a potential question that may solve your problem. – crashmstr Dec 28 '16 at 12:57

1 Answers1

3

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)
{

}
Dawid Wekwejt
  • 533
  • 1
  • 4
  • 19
  • Got the compiler error - `'System.Activities.Statements.TransactionScope': type used in a using statement must be implicitly convertible to 'System.IDisposable'` – Anup Dec 28 '16 at 13:15
  • Use TransactionScope from System.Transactions namespace: – Dawid Wekwejt Dec 28 '16 at 13:18
  • Is it necessary to `Dispose` the Object in Catch statement if there is error? – Anup Dec 29 '16 at 11:35
  • @Anup It isn't necessary to call **Dispose** in **catch** or **finally** block. When program goes out of **using** it invokes **Dispose** – Dawid Wekwejt Dec 29 '16 at 12:51