CallumVass
CallumVass

Reputation: 11458

The context cannot be used while the model is being created

In my application I receive the following error:

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

I'm not sure what this means. I have done everything as normal and usually it works but for this one it isnt. Below is my code:

App.config:

 <connectionStrings>
    <add name="DatabaseContext" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
 </connectionStrings>

Products.cs:

class Products
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

DatabaseContext.cs:

class DatabaseContext : DbContext
{
    public DbSet<Products> Products { get; set; }
}

Program.cs:

DatabaseContext context = new DatabaseContext();

try
{
   var products = context.Products.ToList();

   foreach (var item in products)
   {
      Console.WriteLine(item.ProductID + " : " + item.ProductName);
   }
      Console.ReadLine();
}

The line is fails on is var products = context.Products.ToList();

Any ideas what could be causing this? I have set up 2 products in my database so it should be outputting them.

EDIT

Here is my whole App.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>
  <connectionStrings>
    <add name="DatabaseContext" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />
      </parameters>
    </defaultConnectionFactory>
  </entityFramework>
</configuration>

Upvotes: 29

Views: 79319

Answers (14)

vapcguy
vapcguy

Reputation: 7545

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<Model1>(new CreateDatabaseIfNotExists<Model1>());            
            //this.Configuration.LazyLoadingEnabled = false;

            Database.SetInitializer<Model1>(null);
            this.Configuration.ProxyCreationEnabled = false;

            ((IObjectContextAdapter)this).ObjectContext.ContextOptions.LazyLoadingEnabled = enableLazyLoading;          
            ((IObjectContextAdapter)this).ObjectContext.ContextOptions.ProxyCreationEnabled = enableLazyLoading;
        }

        public virtual DbSet<Product> 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.

Upvotes: 0

Zach Painter
Zach Painter

Reputation: 198

I also had the same issue... However, My problem was that I was using a custom role provider. This role provider had a reference to my context that remained open the entire lifespan of the application. This wasn't an issue until multiple web browsers were attempting to make requests at the same time.

My solution was to create a new context in the custom RoleProvider in each overridden method and dispose via the using statement.

using(var ctx = new Entities())
{
    //do stuff                
}

So, basically if you are getting this error you need to look at your stack trace and see which method / file the error is occurring on and then modify the offending method / class to dispose of the context each time.

In my case I use Ninject DI and have implemented DI on my custom role provider and also in a custom actionfilter. To fix the issue of multiple threads accessing the same context I scrapped the DI in these classes and when straight to creating a new context for each class.

Upvotes: 0

user786
user786

Reputation: 4374

One wrong thing in your code is always use DB context in using block. DB context is not thread safe. And is better used one instant per request

Upvotes: 0

Siva Sankar Gorantla
Siva Sankar Gorantla

Reputation: 562

I also came across same issue today.
In my case restarting Visual Studio resolved the issue.

Upvotes: 1

Jebasingh
Jebasingh

Reputation: 11

Solved by the following:

I had the same issue in my application and resolved by using the below.

  1. Verify your Model names and the table names and it should be matched.

  2. Datatype and Column names used in the model and the database table column name/ Datatype should be matched.

  3. use the below code in your Context class

    Public class MVCRepositoryContext : DbContext 
    {
        static MVCRepositoryContext()
        {
            Database.SetInitializer < mvcrepositorycontext > (null);
        }
    
        public MVCRepositoryContext():base("MVCRepositoryContext"){ }
    
        public virtual DbSet<customer> Customers { get; set; }
    
        public virtual DbSet<book> Books { get; set; }
    
        public virtual DbSet<author> Authors { get; set; }
    }
    

Upvotes: 1

Ahmet Gokdayi
Ahmet Gokdayi

Reputation: 301

In my case, i was using Code First, and i had forgotten to update the database for the last changes.The context and the database must be the same. If not, enter the following code in the package manager;

Update-Database

Upvotes: 1

Deutsche Mexa
Deutsche Mexa

Reputation: 19

I know this is an old ticket, but i could also help to another people with the same problem, in my case, i was not loading a context in a connection string in the app.config file:

e.g.

<add name="SalesContext" connectionString="" providerName="System.Data.SqlClient" />

This should works.

Greetings.

Upvotes: 0

nurdyguy
nurdyguy

Reputation: 2945

I had this error as well but was able to solve it by declaring a local variable context inside of each thread rather than using the one I had declared globally.

    Parallel.ForEach(myList, l=>
    {
        MyContext _db = new MyContext();
        // do some stuff....
        _db.Model.Add(....);
        _db.SaveChanges();

    });

Make sure you also set MultipleActiveResultSets=true in your connection string as described above.

Upvotes: 3

Nabeel
Nabeel

Reputation: 83

I had same problem. I checked my Connection String and made sure SQL Server Service is running to resolve this issue.

Upvotes: 0

Carlos B. Vasquez
Carlos B. Vasquez

Reputation: 127

I was able to resolve this issue by adding

MultipleActiveResultSets=true

to the my EF connection string.

I fixed it by adding this multiple thread connection parameter.

Upvotes: 11

Stefan Michev
Stefan Michev

Reputation: 5093

I had the same issue and solved it using following code:

Database.SetInitializer<EntitiesName>(null);

Upvotes: 0

mjbates7
mjbates7

Reputation: 674

In your App.Config file under connectionstrings you had a forward slash (./SQLEXPRESS). Change this to a backslash .\SQLEXPRESS like so:

<add name="DatabaseContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

Upvotes: 18

AlanCai
AlanCai

Reputation: 16

Add DatabaseContext constructor with database catalog name.

public class DatabaseContext : DbContext {
    public DbSet<Products> Products { get; set; }

    public DatabaseContext() : base("ProjectCode") {}
}

Change entityframework config in app.config like this.

<parameter value="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;MultipleActiveResultSets=true" />

Add Annotations to Products class. Make sure your database has a "Products" table with tow fields "ProductId" and "ProductName".

class Products {
    [Key]
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

If still error, try to change you project target framework to use .net framework 4.0.

Upvotes: 0

ntziolis
ntziolis

Reputation: 10231

I have experienced this issue in the past and usually it was due not using the latest version + referencing issue.

Try and get the newest EF version from NuGet for all your projects and see if the error goes away:
http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-released.aspx

UPDATE
Another reason for this error can be that while you create the context the first time and therefore cause the model to be created you create another context on a separate thread. You will have to wait for other context instances to be created after the model creation has completed.

Upvotes: 17

Related Questions