我有一個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!
爲什麼'SaveChange','Complete'在TransactionScope塊之外?這意味着你的'SaveChanges'不是事務的一部分,Complete應該很可能在對象處置異常時失敗。 – 2013-02-21 18:41:12
@LadislavMrnka對不起,我嘗試將代碼編輯到相關部分後,我複製粘貼作業。我像現在一樣將它粘貼在那裏。 – Langdon 2013-02-21 18:59:33
在Complete上設置一個斷點。它正在執行? – usr 2013-02-21 19:21:11