chobo2
chobo2

Reputation: 85835

Rollback with linq to sql?

I have this

Public void CreateUser(params here)
{
   CreateMembership(params here);
   Users newUser = new Users();
   newUser.UserId = 123456
   Context.Users.insertOnSubmit();
   Context.Submit();
}

public void CreateMembership(...)
{
    Membership membership = new Membership();
     membership.Something = "something";
     Context.Membership.insertOnSumbit();
     Context.Submit();
}

So what happen if the Users table submit fails how can I rol this back to delete the Membership stuff? Or can I setup my thing differently like only remove the Context.Submit() line out of the Membership method?

Then only one Submit gets called? Or do I have to do something else?

Upvotes: 2

Views: 4861

Answers (3)

Jirapong
Jirapong

Reputation: 24256

Using of TransactionScope should be my suggestion.

using (TransactionScope ts = new TransactionScope())
{
    myContext.SubmitChanges();
    ts.Complete();
}

It will rollback, if any exceptions throw from SubmitChanges() method.

Upvotes: 7

Gregory
Gregory

Reputation: 501

You only call submit after all the changes you would like bundled into a single transaction are applied to the LINQToSQL context.

Essentially, remove the Context.Submit(); from the CreateMembership function, and you will acheive the result you are looking for.

Upvotes: 2

leppie
leppie

Reputation: 117280

IMO, you should only call submit once.

Alternatively, I have a method to 'clear' the pending changes.

Have a look here.

Upvotes: 5

Related Questions