2011-07-12 66 views
1

我首先創建SaveChanges並執行異常(UpdateException)。 我做了第二個SaveChanges和againe fliyng第一個erorr。 怎麼辦呢如何取消SaveChanges

bool isUpdate = false; 
var resource = new Resource() { url = tbUrl.Text }; 
//block1 
try 
{ 
    context.Resource.AddObject(resource); 
    context.SaveChanges(); 
    isUpdate = true; 
} 
catch (UpdateException ex) 
{ 

} 

//block2 
if (!isUpdate) 
{ 
    resource = (from res in context.Resource where res.url == tbUrl.Text select res).First(); 
    context.NameToResourcer.AddObject(new NameToResourcer() 
        { 
         id_resource = resource.id, 
         name = tag 
        }); 
    context.SaveChanges();//error! 
} 

回答

2

您對SaveChanges呼叫應在一個事務包裹。通常使用TransactionScope。然後,如果SaveChanges的其中一個調用失敗,您可以回滾該事務。


編輯:

對於一些例子,看看這些2 MSDN網頁:

System.Transactions.TransactionScope Class

How to: Manage Transactions in the Entity Framework

+0

我,你聽到這個消息,你可以品嚐? – Mediator

+0

請參閱上面我的答案中的編輯。我添加了一些有用的鏈接,其中包含示例。 – CodingWithSpike