1

I want to update tables using ExecuteCommand() in below manner:

using (var context = new FMDataContext())
{
    // how do I execute below two steps in a single transaction?
    context.ExecuteCommand("Update Table1 set X = 1 Where Y = 2");
    context.ExecuteCommand("Update Table2 set X = 3 Where Y = 4");
}

There is an answer here for this but it's for EF, I am using Linq To Sql.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
AbbasFaisal
  • 1,428
  • 2
  • 18
  • 21
  • 1
    Possible duplicate of [Using Transactions or SaveChanges(false) and AcceptAllChanges()?](https://stackoverflow.com/questions/815586/using-transactions-or-savechangesfalse-and-acceptallchanges) [Second answer] – SᴇM Apr 16 '19 at 12:14
  • you span a transaction scope around your calls and around your using statement – Mong Zhu Apr 16 '19 at 12:15
  • @SᴇM That answer is for EF. I am using Linq-To-Sql. See https://www.c-sharpcorner.com/blogs/different-between-linq-to-sql-and-entity-framework. – AbbasFaisal Apr 16 '19 at 12:21
  • @AbbasFaisal you are not using Linq2Sql you are using rawsql. You are using the DataBase-Context at most. – Mong Zhu Apr 16 '19 at 14:43
  • 1
    @MongZhu My context class inherits from DataContext in System.Data.Linq namespace. It says "Represents the main entry point for the LINQ to SQL framework." above the definition. May be I should say I am executing rawsql using Linq2Sql DataContext. – AbbasFaisal Apr 16 '19 at 15:29
  • 1
    That would be a better description. If you would use linq2sql you wouldn't need any strings. You would use the given query syntax – Mong Zhu Apr 17 '19 at 18:12

1 Answers1

2

you need to span a TransactionScope around your calls:

using (TransactionScope transaction = new TransactionScope())
{

    using (var context = new FMDataContext())
    {            
        context.ExecuteCommand("Update Table1 set X = 1 Where Y = 2");
        context.ExecuteCommand("Update Table2 set X = 3 Where Y = 4");
    }
    transaction.Complete();
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76