In my application I receive the following error:
The context cannot be used while the model is being created.
I\'m not sure what
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.
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" />
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
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
Solved by the following:
I had the same issue in my application and resolved by using the below.
Verify your Model names and the table names and it should be matched.
Datatype and Column names used in the model and the database table column name/ Datatype should be matched.
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; }
}
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.