在Linq中使用ExecuteCommand来将SQL与事务一起使用

时间:2019-04-16 12:08:25

标签: c# linq-to-sql

我想以以下方式使用ExecuteCommand()更新表:

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");
}

对此有一个答案here,但它是针对EF的,我正在使用Linq To Sql

1 个答案:

答案 0 :(得分:1)

您需要在通话中使用TransactionScope

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();
}