No connection string named 'MyEntities' could be found in the application config file
I am using entity framework and ASP.NET MVC 4 to build an application
My solution is split into two projects;
- A class library that includes my data model (.edmx) file and a few custom interfaces
- The 'container' MVC project that references the class library above
My problem is that when I attempt to use the 'MyEntites' DbContext I get the the following error:
No connection string named 'MyEntities' could be found in the application config file.
I guess the problem has something to do with the fact that connection string lies within the app.config of the class library rather than the MVC project.
Does anyone have any suggestions?
Solution 1:
Try copying the connections string to the .config file in the MVC project.
Solution 2:
You are right, this happens because the class library (where the .edmx file) is not your startup / main project.
You'll need to copy the connection string to the main project config file.
Incase your startup / main project does not have a config file (like it was in my Console Application case) just add one (Startup project - Add New Item -> Application Configuration File).
More relevant information can be found here: MetadataException: Unable to load the specified metadata resource
Solution 3:
make sure that you make your project (with the DbContext) as startup
OR
Add to the project that is set as startup your connection string in the app.config (or web.config)
OR
Call the command like this
Update-Database -Script -ProjectName '<project name>' -StartupProjectName '<project name>' -ConnectionString 'data source=.;initial catalog=<db name>;integrated security=True;MultipleActiveResultSets=True' -ConnectionProviderName 'System.Data.SqlClient'
Then try again
Solution 4:
You could just pass the connection string to EntityFramework
and get on with your life:
public partial class UtilityContext : DbContext
{
static UtilityContext()
{
Database.SetInitializer<UtilityContext>(null);
}
public UtilityContext()
: base("Data Source=SERVER;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD;MultipleActiveResultSets=True")
{
}
// DbSet, OnModelCreating, etc...
}
Solution 5:
copy connection string to app.config
or web.config
file in the project which has set to "Set as StartUp
Project" and if in the case of using entity framework in data layer project - please install entity framework nuget in main project.