在Linq中使用ExecuteCommand到带有Transaction的Sql

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Linq中使用ExecuteCommand到带有Transaction的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

答案

你需要在你的电话周围跨越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();
}

以上是关于在Linq中使用ExecuteCommand到带有Transaction的Sql的主要内容,如果未能解决你的问题,请参考以下文章