0

I have a code like this:

public abstract class DataContextBase
{
    public DbContext DbContext { get; protected internal set; }
    public ObjectContext ObjectContext { get; protected internal set; }
    protected DbTransaction transaction;

    protected void SetContext(DbContext db, ObjectContext oc)
    {
        DbContext = db;
        ObjectContext = oc;
    }

    public void BeginTransaction()
    {
        if (ObjectContext.Connection.State != System.Data.ConnectionState.Open)
        {
            ObjectContext.Connection.Open();
        }
        transaction = ObjectContext.Connection.BeginTransaction();
    }

    public void CommitTransaction()
    {
        try
        {
            transaction.Commit();
        }
        finally
        {
            transaction = null;
            ObjectContext.Connection.Close();
        }
    }

    public void RollbackTransaction()
    {
        try
        {
            transaction.Rollback();
        }
        finally
        {
            transaction = null;
            ObjectContext.Connection.Close();
        }
    }

    public void Save()
    {
        DbContext.SaveChanges();
    }
}

It is from a sample application, and I use this as a base class of my application's main data context. I'm using Entity Framework 5, and I have just read that when I call the DbContext's SaveChanges method, it always runs in a database transaction and it will throw an exception when the transaction have to be rollbacked and in this case the changes are not saved into the database.

But in the sample application, almost every service method begins with a DataContextBase.BeginTransaction call and ends with a DataContextBase.CommitTransaction call (in an exceptional case it ends with DataContextBase.RollbackTransaction) even though that DataContextBase.Save is called (which calls DbContext.SaveChanges()).

It looks like there is an extra transaction wrapping the built in transaction of the DbContext.SaveChanges call.

Could there be any situation which needs this extra transaction?

NOTE: The DataContextBase's ObjectContext is come from the DbContext with a trick:

((IObjectContextAdapter)this).ObjectContext; // inside the DbContext class
4

1 回答 1

2

Having an extra transaction is redundant because ObjectContext/DbContext implements Unit of Work. If you have other means of communicating with the database and they also need to be part of the transaction the use TransactionScope.

Connection management is also done by EF and you do not have to

于 2012-09-07T06:29:44.270 回答