我创建了first SaveChanges and and (UpdateException)。我犯了第二个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!
}发布于 2011-07-13 04:17:58
您对SaveChanges的调用应该包装在一个事务中。通常使用TransactionScope。然后,如果其中一个对SaveChanges的调用失败,则可以回滚事务。
编辑:
有关一些示例,请参阅以下两个MSDN页面:
System.Transactions.TransactionScope Class
How to: Manage Transactions in the Entity Framework
https://stackoverflow.com/questions/6670487
复制相似问题