29

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>
CallumVass
  • 11,288
  • 26
  • 84
  • 154
  • Is this the only code in your application? No database initializer? No concurrent calls (multiple threads, multiple application instances, etc.)? – Ladislav Mrnka Mar 17 '12 at 12:51
  • Yea, this is the only code that uses the database, there is no concurrent calls, its just a basic console app for now – CallumVass Mar 17 '12 at 12:59
  • Have you solved this yet? I have the same problem... – kalasp Apr 16 '13 at 12:45
  • Yes, check the answer I marked as a solution. In my case I was using a forward slash (/) instead of a back slash (\\) – CallumVass Apr 16 '13 at 13:59
  • I was getting the same error just because my sql server service was in stopped state. – RBT Jun 07 '16 at 09:02

14 Answers14

18

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" />
mjbates7
  • 674
  • 1
  • 6
  • 15
  • 1
    @TomW I think it helps because any connection string issue that causes an error can potentially throw the error that OP asked about. I accidentally replaced the DefaultConnection connection string (that comes with new MVC web app) with my MySQL connection string and I received the same error. Even though I wasn't using it the code was still referring to it. – Quinton Smith Feb 22 '16 at 05:43
  • 1
    I had a missing connection string causing this error. – wmcainsh Jul 01 '16 at 11:03
  • Mine was an issue with the connection string. – Caverman Mar 02 '20 at 21:47
  • @TomW When getting the connection string, if you have a forward slash, the code retrieving it will be expecting it to be escaped. If you have only one, it will negate the whole rest of the string. – vapcguy May 19 '20 at 08:38
16

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.

ntziolis
  • 10,091
  • 1
  • 34
  • 50
  • I'm using 4.3.1 version of EF, which is the latest version – CallumVass Mar 17 '12 at 13:26
  • 10
    @BiffBaffBoff Another reason for this error is multithreading. Are you accessing the context from multiple threads? Because the model is created when the `DatabaseContext` is first instantiated, when you try to create another instance of `DatabaseContext` you will also receive this error, you have to wait for the model creation to be ready – ntziolis Mar 17 '12 at 13:33
  • I'm not calling the context in another place in my app, I have only created this small console application to test EF and how it works. – CallumVass Mar 17 '12 at 14:15
  • @ntziolis Please add your comment as an answer, it was the problem in my case! – Peter Morris Dec 08 '16 at 10:08
11

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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • This solved my issue. I had two threads created by WebAPI that queried the context at the same time. By turning on MARS, it resolved the issue entirely. Consider this solution if you are using a multi threaded environment, like WebAPI. – allen1 Jun 22 '15 at 17:37
  • 2
    This is bad advice. MARS is a workaround hiding an underlying issue. – shortstuffsushi Oct 27 '16 at 16:37
  • sadly I experience this problem with 6.1.3 and I have already enabled this feature. – LuckyLikey Aug 07 '17 at 12:08
  • @shortstuffsushi Actually, the underlying issue is that the DBContext is not thread-safe and therefore you are not supposed to create multiple instances of it. By turning it on, you can now do this - you just run a risk of threads being locked when trying to open a database connection, is all. – vapcguy May 19 '20 at 08:40
3

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.

nurdyguy
  • 2,876
  • 3
  • 25
  • 32
1

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
Ahmet Gokdayi
  • 301
  • 9
  • 14
1

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; }
    }
    
smttsp
  • 4,011
  • 3
  • 33
  • 62
Jebasingh
  • 11
  • 1
1

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

0

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

Database.SetInitializer<EntitiesName>(null);
Stefan Michev
  • 4,795
  • 3
  • 35
  • 30
  • I am also facing the same problem. Could you please explain where should I keep above line of code in the class – Ravinder Gangadher Feb 01 '14 at 11:38
  • For a MVC Project the best place to put this code is the Start function in Global.asax file protected void Application_Start() { /*here*/ } – Stefan Michev Feb 02 '14 at 13:50
  • 1
    This answer doesn't make any sense without an explanation. Consider adding why you're doing this, and whether it's an "acceptable" solution, or just a temporary workaround. – shortstuffsushi Oct 27 '16 at 16:35
0

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

Nabeel
  • 73
  • 9
0

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.

0

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

user786
  • 3,902
  • 4
  • 40
  • 72
0

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.

Zach Painter
  • 180
  • 1
  • 9
0

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.
vapcguy
  • 7,097
  • 1
  • 56
  • 52
0

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.

AlanCai
  • 16
  • 2
  • I'm not sure how this will fix it as my class name is the same name as the connection string name anyway? But i've tried this and still get the same error – CallumVass Mar 17 '12 at 14:19