The context cannot be used while the model is being created

前端 未结 14 1345
渐次进展
渐次进展 2020-12-03 13:27

In my application I receive the following error:

The context cannot be used while the model is being created.

I\'m not sure what

14条回答
  •  一生所求
    2020-12-03 14:12

    1 - Ensure that the Connection String has a backslash instead of a forward slash:

    connectionString="Data Source=.\SQLEXPRESS ....
    

    2 - Add MultipleActiveResultSets=true to the connection string.

    3 - What was causing it for me was that I had multiple constructors to my DbContext class:

    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.ModelConfiguration.Conventions;
    
    namespace MyProject
    {
        public partial class Model1 : DbContext
        {
            // I had to comment out this one ...
            //public Model1()
            //    : base("name=Model1")
            //{
            //}
    
            public Model1(bool enableLazyLoading = true)
                : base("name=Model1")
            {
                //Database.SetInitializer(new CreateDatabaseIfNotExists());            
                //this.Configuration.LazyLoadingEnabled = false;
    
                Database.SetInitializer(null);
                this.Configuration.ProxyCreationEnabled = false;
    
                ((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = enableLazyLoading;          
                ((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = enableLazyLoading;
            }
    
            public virtual DbSet Products { get; set; }
            // ...
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                // ...
            }
        }
    }
    

    Once I commented out the original Model1 constructor it solved it.

    I left 2 versions of the Lazy Loading/Database.SetInitializer to show there are 2 ways to do it - either enabled or disabled.

    • If you use the first 2 lines to NOT use it, don't use the next 4 and remove bool enableLazyLoading = true.
    • If you DO use the 4 lines like shown, ensure you keep those 2 lines commented out and keep the bool enableLazyLoading = true.

提交回复
热议问题