EF6交易回滚&并发问题

时间:2016-02-08 14:26:55

标签: c# entity-framework transactions

一旦我回滚我的事务并再次尝试,它就会因 DbUpdateConcurrencyException 而失败。

在查看SQL分析器之后,我发现第一次发送INSERT查询时,正如预期的那样,第二次尝试更新,即使第一次回滚了吗?!

首先查询:

exec sp_executesql N'INSERT [dbo].[FiscalReceipt]([PurchaseTime], [ReceiptNumber], [Cash], [Card], [Bank])
VALUES (@0, @1, @2, @3, @4)
SELECT [FiscalReceiptID]
FROM [dbo].[FiscalReceipt]
WHERE @@ROWCOUNT > 0 AND [FiscalReceiptID] = scope_identity()',N'@0 datetime2(7),@1 int,@2 decimal(18,2),@3 decimal(18,2),@4 decimal(18,2)',@0='2016-02-08 15:05:43.9145089',@1=666,@2=1.70,@3=0,@4=0

第二次查询:

exec sp_executesql N'UPDATE [dbo].[FiscalReceipt]
SET [PurchaseTime] = @0, [Cash] = @1
WHERE ([FiscalReceiptID] = @2)
',N'@0 datetime2(7),@1 decimal(18,2),@2 int',@0='2016-02-08 15:12:11.8101261',@1=555.00,@2=2042

P.S。在提交内容时,不应该有SQL:Rollback或TM:在SQL事件探查器表的EventClass列中提交吗?

C#代码:

注意: OutOfPaperException旨在被忽略,并且该范围内的事务是故意提交的。应该在任何其他例外情况下回滚更改。

var transaction = DatabaseContext.Database.BeginTransaction();

            try
            {
                // Commented for debugging
                //IFiscalPrinter fPrinter = DeviceManager.GetFiscalPrinter();
                //var lastReceiptNumber = fPrinter.GetLastReceiptNumber();

                // false data for debugging
                var lastReceiptNumber = 666;
                Receipt.ReceiptNumber = lastReceiptNumber++;
                Receipt.PurchaseTime = DateTime.Now;

                DatabaseContext.SaveChanges();

                //fPrinter.PrintFiscalReceipt(Receipt);

                // Exception for debugging purpose
                if (Receipt.Cash < 500)
                {
                    throw new Exception();
                }

                transaction.Commit();

                Close();
            }
            catch (OutOfPaperException)
            {
                if (transaction != null)
                {
                    transaction.Commit();
                    Close();
                }

                MessageBoxService.ShowMessage("Promenite papir pre sledećeg štampanja!", "Nema više papira!", MessageButton.OK, MessageIcon.Warning);
            }
            catch (Exception ex)
            {
                // I added this but this doesn't help
                Receipt.PurchaseTime = new DateTime();
                Receipt.ReceiptNumber = 0;
                //Receipt.FiscalReceiptID = 0; <- I'm not allowed to do this

                if (transaction != null)
                {
                    transaction.Rollback();
                }

                MessageBoxService.ShowMessage(ex.Message, "Greška!", MessageButton.OK, MessageIcon.Error);
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }
            }

DatabaseContext生命周期等于ViewModel的生命周期。

编辑:将相应的条目状态更改为EntryState.Added会导致操作成功,但感觉很脏。事务回滚/失败时,条目是否应保持在已添加状态?

EDIT2:运行此代码后:

using (MetalShopDB ctx = new MetalShopDB())
using (var transaction = ctx.Database.BeginTransaction())
{
    var receipt = new FiscalReceipt()
    {
        ReceiptNumber = 555,
        PurchaseTime = DateTime.Now,
        Cash = 100
    };

    ctx.FiscalReceipts.Add(receipt);

    Console.WriteLine("Has changes " + ctx.ChangeTracker.HasChanges());
    Console.WriteLine(ctx.Entry(receipt).State);

    ctx.SaveChanges();

    Console.WriteLine("Saved changes");

    Console.WriteLine("Has changes " + ctx.ChangeTracker.HasChanges());
    Console.WriteLine(ctx.Entry(receipt).State);

    transaction.Rollback();

    Console.WriteLine("Rolled back");

    Console.WriteLine("Has changes " + ctx.ChangeTracker.HasChanges());
    Console.WriteLine(ctx.Entry(receipt).State);
}

我得到了这个输出,我觉得这很奇怪,因为人们希望上下文与db同步,所以当你回滚时,上下文应该跟着改变。

Has changes True
Added
Saved changes
Has changes False
Unchanged
Rolled back
Has changes False
Unchanged

1 个答案:

答案 0 :(得分:2)

对于您的EDIT2

当调用SaveChanges方法时,如果在保存时没有找到错误(自从您回滚以后就是这种情况),则调用 ObjectContext.AcceptAllChanges()方法接受更改并填充主键,外键和更改进入状态。

回滚仅回滚事务而不回滚对象上下文/更改跟踪器。

此时要再次调用SaveChanges,因为实体已经填充了数据库信息,即使您进行了回滚。

原始问题

在SaveChanges 成功完成后抛出错误(用于调试)

if (Receipt.Cash < 500)
{
    throw new Exception();
}

因此,通过遵循先前的逻辑,已经调用了AcceptAllChanges。

修改

您可以使用ObjectContext

进行保存来控制AcceptAllChanges
var objectContext = ((IObjectContextAdapter) ctx).ObjectContext;
objectContext.SaveChanges(SaveOptions.DetectChangesBeforeSave);

transaction.Commmit();
objectContext.AcceptAllChanges();