Entity Framework Code First Transaction

advertisements

I am using Entity Framework 4 with SqlServer CE as the database.

Because SqlServer CE does not support TransactionScope, so I have to resort to using BeginTransaction and RollbackTransaction method.

I have two GRUD functions to delete and create rows in the database.

What I want to achieve is something like this :

    using (var context = new MyContext())
                {
                    using (var tx = context.BeginTransaction())
                    {
                       // grud functions
                       deleteRows();
                       addRows();

                       // do db stuff here...
                       tx.Commit();
                    }
                }

But I cannot find BeginTransaction in the context.

How can I go about it?


How can I go about it

I think, you're misunderstanding a concept of DbContext. It is a local cache of entities + change tracker. Whatever you do with entities, this changes are just tracked by context without affecting underlying data source.

This all happens until you call SaveChanges method. This method applies changes from change tracker to data source in transaction manner, so, all of the changes you've made, will be consistent.

If you will write your deleteRows and addRows in a way, that they won't call SaveChanges, and put SaveChanges call somewhere outside these methods, you'll get desired transaction:

using (var context = new MyContext())
{
    // grud functions
    deleteRows(context);
    addRows(context);

    context.SaveChanges();
}

private void deleteRows(MyContext context) {}
private void addRows(MyContext context) {}