开发者

How cancel SaveChanges

I make first SaveChanges and flies exception (UpdateException). And I make second SaveChanges and againe fliyng first erorr. What to do about it

bool isUpdate = false;
var resource = new Resource() { url = tbUrl.Text };
//block1
try
{
    context.Resource.AddObject(resource);
    context.SaveChanges();
    isUpdate = t开发者_开发知识库rue;
}
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!
}


Your calls to SaveChanges should be wrapped in a transaction. Typically using a TransactionScope. Then you can roll-back the transaction if one of the calls to SaveChanges fails.


Edit:

For some examples, see these 2 MSDN pages:

System.Transactions.TransactionScope Class

How to: Manage Transactions in the Entity Framework

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜