DbContext在负载增加时被处理(在负载测试期间)

时间:2015-04-17 06:15:45

标签: c# entity-framework idisposable

我们的项目是在Base类中创建DbContext,所有其他数据访问层都从它继承。 Base类实现IDisposable并处理所有dispose工作。在正常流程中一切正常,但在负载测试期间我们开始

"Exception type: System.InvalidOperationException

Message       : The operation cannot be completed because the DbContext has been disposed.
"

任何dispose都不会在子类中处理,一个数据访问层也会不断调用其他数据访问层来重用DAL方法。

基类:

  public class DataAccessBase : IDisposable
    {

        protected DbDataContext dataContext = null;

        public DataAccessBase()
        {
            dataContext = new DbDataContext();
        }


        public DataAccessBase(DbDataContext dataContext)
        {
            if (dataContext==null )
                dataContext = new DbDataContext();

            this.dataContext = dataContext;
        }

        // NOTE: Leave out the finalizer altogether if this class doesn't 
        // own unmanaged resources itself, but leave the other methods
        // exactly as they are. 
        ~DataAccessBase()
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }

        // Dispose() calls Dispose(true)
        public void Dispose()
        {

            Dispose(true);
            GC.SuppressFinalize(this);
        }

        // The bulk of the clean-up code is implemented in Dispose(bool)
        protected  virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // free managed resources
            }
            // get rid of unmanaged resources
            if (dataContext != null)
            {
                dataContext.Dispose();
            }
        }
    }

在Child类中使用:

 public class HelpDataAccess : DataAccessBase
    {


        public Help GetHelpRecords (int id)
        {
            try
            {

                return dataContext.Help.FirstOrDefault(h => h.Id == id && h.IsActive);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

           //other methods


    }

因此,这种简单的提取方法失败,DbContext处理错误。

Stack Trace : 

Exception type: System.InvalidOperationException

Message       : The operation cannot be completed because the DbContext has been disposed.

Stacktrace:
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.LazyInternalContext.get_ObjectContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.CreateObjectQuery(Boolean asNoTracking, Nullable`1 streaming, IDbExecutionStrategy executionStrategy)
   at System.Data.Entity.Internal.Linq.InternalSet`1.InitializeUnderlyingTypes(EntitySetTypePair pair)
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)

- 我们尝试了许多建议,但没有任何东西正在帮助。 知道为什么会这样吗?

感谢阅读!

0 个答案:

没有答案