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.
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>
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With