【问题标题】:Entity Framework.Is it possible and recommended to use transaction within context multiple times.?实体框架。是否可以并建议在上下文中多次使用事务。?
【发布时间】:2019-05-17 09:09:52
【问题描述】:

例如我有这样的代码

using (AccountingEntities ent = new AccountingEntities())
{
    //just to read record
    var recs = ent.Payments.Where(pp => pp.PaymentId == 123);

    foreach (p in recs)
    {
        if (p.Status == 1)
        {
            using (var dbContextTransaction = ent.Database.BeginTransaction())
            {
                var someotherrecs = ent.SomeTable.Where(s => s.PaymentId == 456);
                foreach (var rec in someotherrecs)
                {
                    rec.Status = 2;
                }
                ent.SaveChanges();
                dbContextTransaction.Commit();
            }
        }
    }
}

如果我不必更改记录,我将避免启动事务,可能在 90% 的情况下。是否可以执行此类操作(在单个上下文中启动和完成多个事务)?

【问题讨论】:

  • SaveChanges 会自动为您执行此操作。
  • @IvanStoev 但它会产生异常,还是错过写入更改?
  • 如果您在一个事务中有多个SaveChanges 调用,这将是有意义的(也许)。有时这是不可避免的。

标签: c# entity-framework transactions dbcontext


【解决方案1】:

正如@Ivan Stoev 在评论中提到的那样,您根本不需要在这里进行交易。 阅读文档https://docs.microsoft.com/ru-ru/dotnet/api/system.data.objects.objectcontext.savechanges?view=netframework-4.8

在那里找到:

SaveChanges 在事务中运行。

所以,EF 有一个 changetracker,它可以跟踪对实体的任何更改。当您执行 SaveChanges 时,在单个事务中所有更改都将被提交或回滚以防出现异常。

所以你的代码可能看起来像:

using (AccountingEntities ent = new AccountingEntities())
{
    //just to read record
    var recs = ent.Payments.Where(pp => pp.PaymentId == 123);

    foreach (p in recs)
    {
        if (p.Status == 1)
        {
                var someotherrecs = ent.SomeTable.Where(s => s.PaymentId == 456);
                foreach (var rec in someotherrecs)
                {
                    rec.Status = 2;
                }
                ent.SaveChanges();

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多