2012-05-15 26 views
1

我想知道如何保存多個對象的最佳方式是,如果第二個'obj.Insert()'拋出異常,所有更改都會回滾。在一次提交中保存來自不同類的多個對象

我a'm嘗試類似的東西:

Product product1 = new Product(); 
Product product2 = new Product(); 
Product product3 = new Product(); 

DbContext DB = new DB(); 

IProductInsert repository = new ProductInsert(DB); 

repository.Insert(product1); 
repository.Insert(product2); 
repository.Insert(product3); 

DB.SaveChanges(); 

但是,在我看來,我認爲這是不正確..

如何節省使用DB所有更改或回滾.SaveChanges()在我的存儲庫類?

回答

1

你應該能夠與交易範圍,做到這一點:

using (var ts = new TransactionScope()) { 
    repository.Insert(product1); 
    repository.Insert(product2); 
    repository.Insert(product3); 
    DB.SaveChanges(); 
    ts.Complete(); 
} 

如果有什麼事情在這個序列中失敗,並沒有達到呼叫ts.Complete(),後臺事務回滾。

有關跨多個數據庫上下文工作的解決方案,請參閱this answer

+0

Niceeee ..但VS沒有找到System.Transaction ..爲什麼? – MuriloKunze

+0

@murilokunze您需要將對System.Transactions的引用添加到項目的引用列表中(右鍵單擊「References」,選擇「Add Reference ...」,然後打開「.NET」選項卡並添加' System.Transactions')。 – dasblinkenlight

+0

現在它的工作:) ..但我有一個更多的疑問..我應該在我的視圖中使用transactionScope? – MuriloKunze

相關問題