Automatic transaction management datacontext

I assumed that when using a DataContext I get an automatic rollback:

UPDATE I actually called SubmitChangestwice, 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 a rollback, I 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 much more than i want. Is there a better way to tell the DataContext that you want automatic rollback?

+3
source share
1 answer

If not inside an external transaction (for example TransactionScope), it SubmitChangesstarts the transaction for you and automatically rolls back if an exception occurs.

Suggest posting the actual code causing the problem and the exception that occurred.

SubmitChanges , , TransactionScope:

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

    blah2.SubmitChanges();

    ts.Commit();
}
+4

Source: https://habr.com/ru/post/1792989/


All Articles