C# – 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:


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


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


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


DatabaseContext context = new DatabaseContext();

   var products = context.Products.ToList();

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

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.


Here is my whole App.config file:

<?xml version="1.0" encoding="utf-8"?>
    <!-- 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=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <add name="DatabaseContext" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=ProjectCode;Integrated Security=SSPI;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
        <parameter value="Data Source=.\SQLEXPRESS; Integrated Security=True; MultipleActiveResultSets=True" />

Best Solution

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" />
Related Question