【问题标题】:How to roll back queries in C#?如何在 C# 中回滚查询?
【发布时间】:2016-12-28 12:54:30
【问题描述】:

我有删除查询列表,我使用以下代码执行它们:

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

我想提交所有删除查询,但如果任何查询出现错误,我想回滚。

上述场景如何回滚?

【问题讨论】:

标签: linq asp.net-mvc-4 model-view-controller entity-framework-6


【解决方案1】:

尝试使用 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)
{

}

【讨论】:

  • 得到编译器错误 - 'System.Activities.Statements.TransactionScope': type used in a using statement must be implicitly convertible to 'System.IDisposable'
  • 使用 System.Transactions 命名空间中的 TransactionScope:
  • Object in Catch语句有错误需要Dispose吗?
  • @Anup 不需要在 catch 或 finally 块中调用 Dispose。当程序退出 using 时,它会调用 Dispose
猜你喜欢
  • 2010-10-17
  • 1970-01-01
  • 2020-12-18
  • 2021-09-22
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 2017-08-01
  • 2019-08-02
相关资源
最近更新 更多