Mediator
Mediator

Reputation: 15378

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 = 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!
}

Upvotes: 1

Views: 980

Answers (1)

CodingWithSpike
CodingWithSpike

Reputation: 43748

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

Upvotes: 2

Related Questions