DbContext不断抛出“在创建模型时不能使用上下文”。异常

时间:2016-03-31 21:22:04

标签: c# .net entity-framework odp.net odp.net-managed

我正在开发一个新的应用程序,它正在使用Entity Framework 6,ODP.NET,Oracle Managed Driver for Entity Framework和Oracle数据库。

我所看到的是,如果在使用DbContext时抛出异常,则表明它没有正确处置连接或上下文。

我正在使用TDD设计,我的断开连接的调用包含在Repository类中。我正在使用如下语句包装我的DbContext调用:

public class ProductDbRepository : IProductDbRepository
    {
        public ProductDbRepository() { }

        public List<IProduct> GetAll()
        {
            IQueryable<Product> query;
            List<IProduct> list = new List<IProduct>();

            using (var db = new MainContext())
            {
                query = db.Products;

                foreach (var item in query)
                {
                    list.Add(item);
                }
            }

            return list;
        } 
    }

MainContext:

internal class MainContext : DbContext
    {
        internal MainContext() : base("name=OracleDbContext") { }

        public virtual DbSet<Country> Countries { get; set; }
        public virtual DbSet<Product> Products { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<MainContext>(null);

            base.OnModelCreating(modelBuilder);
        }
    }

如果在using语句中引发了异常,例如foreach循环,那么后续请求使用DbConext的其他存储库,我会看到这个错误:

  

创建模型时无法使用上下文。这个   如果在内部使用上下文,则可能抛出异常   OnModelCreating方法或者如果访问相同的上下文实例   并发多个线程。请注意DbContext的实例成员   并且相关的类不保证是线程安全的。“,
  “ExceptionType”:“System.InvalidOperationException”,“StackTrace”:“   在   System.Data.Entity.Internal.LazyInternalContext.InitializeContext(个)\ r \ n   在System.Data.Entity.Internal.InternalContext.Initialize()\ r \ n at   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(类型   entityType)\ r \ n at   System.Data.Entity.Internal.Linq.InternalSet 1.Initialize()\r\n at System.Data.Entity.Internal.Linq.InternalSet 1.GetEnumerator(个)\ r \ n
  在   System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator(个)\ r \ n

要解决我必须停止调试和IIS Express。在过去使用EF和SQL Server和EF5时,我从未见过这种情况。

我的问题是:如果在使用DbContext时抛出异常,我应该做些什么来确保正确关闭DbContext和连接?

0 个答案:

没有答案