Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automatic datacontext transaction management

I assumed when using DataContext in the following fashion I would get automatic rollback:

UPDATE I actually called SubmitChanges twice but the question still applies.

public void UpdateUser(User user)
    {
        using (var context = new UserDataContext())
        {
            //update stuff.
            context.SubmitChanges();

            //update stuff.
            context.SubmitChanges();
        }
    }

When something goes wrong there is no rollback.

Instead, to provide rollback I've implemented the following:

public void UpdateUser(User user)
    {
        var context = new UserDataContext();
        try
        {
            context.Connection.Open();
            context.Transaction = context.Connection.BeginTransaction();

            //update stuff.
            context.SubmitChanges();
            context.Transaction.Commit();
        }
        catch (Exception e)
        {
            context.Transaction.Rollback();
            throw;
        }
        finally
        {
            context.Dispose();
        }
    }

which is alot more plumbing than I want. Is there a better way to indicate to DataContext you want automatic rollback?

like image 891
wal Avatar asked Jul 22 '26 23:07

wal


1 Answers

If not inside a external transaction (e.g. TransactionScope), SubmitChanges starts a transaction for you and should automatically rollback if an exception occurs.

Suggest you post the actual code causing the problem and the exception that occurs.

If you are performing multiple SubmitChanges and want them to be atomic, wrap in a TransactionScope:

using (TransactionScope ts = new TransactionScope())
{
    blah1.SubmitChanges()

    blah2.SubmitChanges();

    ts.Commit();
}
like image 164
Mitch Wheat Avatar answered Jul 25 '26 12:07

Mitch Wheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!