In my application I receive the following error:
The context cannot be used while the model is being created.
I\'m not sure what
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.
bool enableLazyLoading = true
. bool enableLazyLoading = true
.