2016-02-18 61 views
1

我用下面的代碼片斷然而就是更新一個DataContext交易多DataContexts

// Mark the customer as updated. 
context.UpdateObject(customerToChange); 
// Send the update to the data service. 
context.SaveChanges(); 

我的問題的一個實體,那我有多個DataContexts。

例如,如果我有DataContext A和B,並按此順序保存更改。

那麼現在的行爲是: 如果A成功並且B失敗,那麼它會中止。但變化已經持續到A!

祝願行爲: 如果A成功,B出現故障時也應該回滾A.

所以我的想法是這樣的:

using(TransactionScope tran = new TransactionScope()) { 
    contextA.updateObject(objA); 
    contextB.updateObject(objB); 
    tran.Complete(); 
} 

然而,這似乎不是在多個可能的數據上下文。

您有任何關於如何正確實施OData的想法嗎?

+0

做這些的datacontext代表同一數據庫或不同的數據庫? – Sameer

+0

如果您在完成事務之前保存更改並在客戶端和服務器上啓用MSDTC(如果每個上下文表示不同的數據庫連接),則TransactionScope應該可以工作。 – Sameer

+0

@Sameer始終是相同的數據庫。每個表總是有一個DataContext。我無法改變架構(這是Navision),但這不應該關注你。我唯一擔心的是如何在不改變其他任何東西的情況下跨越多個數據上下文正確實現這一點(鑑於上述簡化的情況)。 –

回答

0

你可以試試這個:

請找裁判: Using Transactions or SaveChanges(false) and AcceptAllChanges()?

using (TransactionScope scope = new TransactionScope()) 
    { 
    //Do something with contextA 
    //Do something with contextB 

    //Save Changes but don't discard yet 
    contextA.SaveChanges(false); 

    //Save Changes but don't discard yet 
    contextB.SaveChanges(false); 

    //if we get here things are looking good. 
    scope.Complete(); 
    contextA.AcceptAllChanges(); 
    contextB.AcceptAllChanges(); 

    } 
+0

感謝您的幫助。但是,DataServiceContext類不提供SaveChanges(false)或AcceptAllChanges()函數。 –

+0

https://msdn.microsoft.com/zh-cn/data/dn456843.aspx @fabian bigler –