E
E
Egor Lavrentiev2015-03-03 07:03:16
C++ / C#
Egor Lavrentiev, 2015-03-03 07:03:16

entity framework. How to use transactions correctly?

Colleagues, welcome!
I have the following code in my app

public static bool DoLargeOperation()
        {
            bool res = true;

            res = res && DoFirstSubOperation();
            res = res && DoSecondSubOperation();
            res = res && DoThirdSubOperation();

            return res;
        }

Each of the internal functions looks something like this:
public static bool DoFirstSubOperation()
        {
            using (var context = new EntityFrameworkContext())
            {
                // Изменение данных.
                context.SaveChanges();
            }
        }

Let's say that the first two internal functions executed without errors, but the third one threw an exception.
How can I undo the result of the first two functions?
This approach didn't work:
using (var transaction = new TransactionScope())
            {
                res = res && DoFirstSubOperation();
                res = res && DoSecondSubOperation();
                res = res && DoThirdSubOperation();
            }

The only solution I see is to declare the context in the method like this:
public static bool DoLargeOperation()
        {
            bool res = true;

            using (var context = new EntityFrameworkContext())
            {
                using (var transaction = context.Database.BeginTransaction())
                {

                    res = res && DoFirstSubOperation(context);
                    res = res && DoSecondSubOperation(context);
                    res = res && DoThirdSubOperation(context);
                    if (res)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Rollback();
                    }
                }
            }

            return res;
        }

But is this option acceptable, or is there some other way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2015-03-03
@YaguarVL

Yes, under such conditions it is the correct option.
If the functions are members of the same class and can be made non-static, then the context can also be made a member of the class. I wouldn't recommend making the context static.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question