2013-02-21 90 views
0

我有一個Publication表和一個Receipt表。當我發佈數據時,我會在Publication表中追蹤它。當我的測試客戶端從代理商處收到該發佈時,我會在Receipt表中跟蹤它。實體框架TransactionScope不回滾

我的Publication表格上有一個非規範化的ReceiptCount列,以方便報告。

在我的測試中,消費者接收的出版,將下面的代碼執行:

try 
{ 
    using (var context = new PublicationVerifierEntities()) 
    { 
     using (var transaction = new TransactionScope()) 
     { 
      if (request.PublicationGuid == Guid.Empty) 
      { 
       context.AddToUnknownPublications(new UnknownPublication 
       { 
        DateReceived = request.DateReceived, 
        Publication = request.Publication, 
       }); 
      } 
      else 
      { 
       // look up the publication by Guid 
       var publication = context.Publications.FirstOrDefault(m => m.PublicationGuid.Equals(request.PublicationGuid)); 

       if (publication == null) 
       { 
        throw new Exception("UpdatePublicationReceipt, provided PublicationGuid not found in database."); 
       } 
       else 
       { 
        context.AddToUnknownPublications(new UnknownPublication 
        { 
         DateReceived = request.DateReceived, 
         Publication = request.Publication, 
        }); 

        context.AddToReceipts(new Receipt 
        { 
         DateReceived = request.DateReceived, 
         Publication = publication, 
        }); 

        publication.ReceiptCount++; 
       } 
      } 

      context.SaveChanges(System.Data.Objects.SaveOptions.None); 
      transaction.Complete(); 
      context.AcceptAllChanges(); 
     } 
    } 
} 
catch (Exception ex) 
{ 
    _logger.Error("Unable to update publication record receipt.", ex); 
    throw; 
} 

的問題是,如果在Receipt插入失敗,則Publication.ReceiptCount永遠不會回滾。若要刪除Receipt表以對其進行測試,並且ReceiptCount列將繼續成功更新,儘管引發了System.Data.UpdateException。我看到在SQL事件探查器下面的查詢執行,但隻字未提回滾:

exec sp_executesql N'update [dbo].[Publication] 
set [ReceiptCount] = @0 
where ([PublicationId] = @1) 
',N'@0 int,@1 int',@0=10,@1=3414639 

exec sp_executesql N'insert [dbo].[Receipt]([PublicationId], [DateInserted], [DateReceived]) 
values (@0, null, @1) 
select [ReceiptId] 
from [dbo].[Receipt] 
where @@ROWCOUNT > 0 and [ReceiptId] = scope_identity()',N'@0 int,@1 datetime',@0=3414639,@1='2013-02-21 18:12:47:513' 

上所以這對方的回答使我相信我做正確的一切:How to rollback a transaction in Entity Framework,所以......

什麼我在這裏想念嗎?

到目前爲止,我已經嘗試使用關於SaveChanges()的每次重載創建的TransactionScope使用語句。沒有什麼改變。

TIA!

+0

爲什麼'SaveChange','Complete'在TransactionScope塊之外?這意味着你的'SaveChanges'不是事務的一部分,Complete應該很可能在對象處置異常時失敗。 – 2013-02-21 18:41:12

+0

@LadislavMrnka對不起,我嘗試將代碼編輯到相關部分後,我複製粘貼作業。我像現在一樣將它粘貼在那裏。 – Langdon 2013-02-21 18:59:33

+0

在Complete上設置一個斷點。它正在執行? – usr 2013-02-21 19:21:11

回答

1

拉起我的意見,因爲他們竟然回答:

你的意見是說,你是不是產生交易(您使用的每個語句隱含的交易)。找出爲什麼TScope沒有采取。嘗試把它放在新的實體之外。請注意,如果TScope不採取任何警告生成。它只是默默無聞。

您的連鎖包含Enlist=false