[c#] 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?

This question is related to c# entity-framework asp.net-mvc-4

The answer is


Add ConnectionString to MVC Project Web.config file


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.


Yeah, it's silly. You can avoid copying the connection string by using a connection builder. VB.Net code (used in production, but slightly modified here, so treat as untested, happy to assist with any issues), where I have a serverName variable, a databaseName variable, I pass them into a method and have it generate the connection for me:

    Dim EfBuilder As New System.Data.EntityClient.EntityConnectionStringBuilder("metadata=res://*/VMware.VmEf.csdl|res://*/VMware.VmEf.ssdl|res://*/VMware.VmEf.msl;provider=System.Data.SqlClient;provider connection string=""data source=none;initial catalog=none;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""")
   Dim SqlBuilder As New Data.SqlClient.SqlConnectionStringBuilder(EfBuilder.ProviderConnectionString)
                        SqlBuilder.DataSource = serverName
                        SqlBuilder.InitialCatalog = databaseName
                        EfBuilder.ProviderConnectionString = SqlBuilder.ConnectionString
                        Using vmCtx As New VmEfConn(EfBuilder.ConnectionString)

I had this error when attempting to use EF within an AutoCAD plugin. CAD plugins get the connection string from the acad.exe.config file. Add the connect string as mentioned above to the acad config file and it works.

Credit goes to Norman.Yuan from ADN.Network.


make sure that you make your project (with the DbContext) as startup

on the project right click and select

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


  1. Add an App.Config file
  2. Set the project as startup project.
  3. Make sure you add the connection strings after entityFramework section:

    <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=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
    
    </configSections>
    
    <connectionStrings>
       <!-- your connection string goes here, after configSection -->
    </connectionString>
    

Add a connection string in the root web.config file of 'container' MVC project that references the class library as following:

 <connectionStrings>

  <add name="MyEntities" connectionString="complete connection string here" providerName="System.Data.SqlClient" />

  </connectionStrings>

If you do not want to use "MyEntities" as connection name then change it as you wish but make the following change in your MyEntities DbContext class:

MyEntities: DbContext
 {
   public MyEntities():base("Name-Of-connection-string-you wish to connect"){ }
 }

Reason for this error is, If we will not specify the name of connection string Or connect string in derived class of DbConext(In your case it is MyEntities) then DbContext will automatically search for a connection string in root web.config file whoes name is same as derived class name (In your case it is My Entities).


If you have multiple projects in solution, then setUp project as started where you have your truth App.config.


are you using more than one project on your solution?

Because if you are, the web config you must check is the one on the same project as de .edmx file


Regular migrations

There are two options - the first one that everyone here has suggested is to ensure that the connection string is in the Web.config file of the project. When working with connection strings from Azure application settings, that means overwriting your Web.config values with the Azure values.

Azure or automatic migrations (programmatic)

There's a second option available if you're running migrations programmatically, that allows you to run migrations using a connection string that's obtained dynamically (or via Azure application settings) without storing it in Web.config:

When setting the configuration's TargetDatabase, use the DbConnectionInfo constructor that takes a connection string and a provider name instead of the constructor that takes just a connection name. If your connection string doesn't have a provider name and you're using SQL Server / Azure SQL then use "System.Data.SqlClient"


If you are using an MVVM model, try to copy the connection strings to all parts of your project.

For example, if your solution contains two projects, the class library project and the wpf project, you must copy the connection strings of the backend project (library class porject) and place a copy in the App.config file of the wpf project.

<connectionStrings>
  <add name="DBEntities" ... />
</connectionStrings>

Hope it's helpful for you :)


It is because your context class is being inherited from DbContext. I guess your ctor is like this:

public MyEntities()
    : base("name=MyEntities")

name=... should be changed to your connectionString's name


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...
}

This could also result in not enough dll references being referenced in the calling code. A small clumsy hack could save your day.

I was following the DB First approach and had created the EDMX file in the DAL Class library project, and this was having reference to the BAL Class library, which in turn was referenced by a WCF service.

Since I was getting this error in the BAL, I had tried the above mentioned method to copy the config details from the App.config of the DAL project, but didn't solve. Ultimately with the tip of a friend I just added a dummy EDMX file to the WCF project (with relevant DB Connectivity etc), so it imported everything necessary, and then I just deleted the EDMX file, and it just got rid of the issue with a clean build.


I had this problem when running MSTest. I could not get it to work without the "noisolation" flag.

Hopefully this helps someone. Cost me a lot of time to figure that out. Everything ran fine from the IDE. Something weird about the Entity Framework in this context.


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


I have faced the same issue. I was missed to put connection string to startup project as I am performing data access operation from other layer. also if you don't have app.config in your startup project then add app.config file and then add a connection string to that config file.


I got this by not having the project set as startup, as indicated by another answer. My contribution to this - when doing Add-Migrations and Update-Database, specify the startup project as part of the command in Nuget Package Manager Console (do not include the '[' or ']' characters, that's just to show you that you need to change the text located there to your project name):

  1. Enable-Migrations
  2. Add-Migrations -StartupProject [your project name that contains the data context class]
  3. Update-Database -StartupProject [same project name as above]

That should do it.


I've had this problem when I use multiple proyects, the start proyect with web.config and app.config for EntityFramework project.

for avoid this problem you must:

  1. You need the connection string in the started *.config file.
  2. You need have installed the EntityFramework DLL into your references

The connection string generated by the project containing the .edmx file generates the connection string, this would appear to be a holdover from the app.config sorts of files that were copied to the output directory and referenced by the executable to store runtime config information.

This breaks in the web project as there is no automatic process to add random .config information into the web.config file for the web project.

Easiest is to copy the connection string from the config file to the connections section of the web.config file and disregard the config file contents.


This problem happen when you are using Layers in your Project and defined or install Entity frame work in DataLayer and try to run your Project

So to overcome from this problem copy the connection string from the layer where the Edmx file is there and paste the connection string in main web.config.


Make sure you've placed the connection string in the startup project's ROOT web.config.

I know I'm kinda stating the obvious here, but it happened to me too - though I already HAD the connection string in my MVC project's Web.Config (the .edmx file was placed at a different, class library project) and I couldn't figure out why I keep getting an exception... Long story short, I copied the connection string to the Views\Web.Config by mistake, in a strange combination of tiredness and not-scrolling-to-the-bottom-of-the-solution-explorer scenario. Yeah, these things happen to veteran developers as well :)


There is a comment on the top answer by @RyanMann that suggests:

Store your connection strings in one config file, then reference them in other projects by <connectionString configSource="../ProjectDir/SharedConnections.config" />

This is a fantastic suggestion!

It also works to share connection strings between App.config and Web.config files!

Anyone wanting to follow this suggestion, should head on over to this SO answer. It has a really great step-by-step guide on sharing connection strings among multiple projects in a solution.

The only caveat is that configSource must exist in the same directory or a sub-directory. The link above explains how to use "Add as Link" to get around this.


As you surmise, it is to do with the connection string being in app.config of the class library.

Copy the entry from the class app.config to the container's app.config or web.config file


Add Connectoinstrnig in web.config file

<ConnectionStiring> <add name="dbName" Connectionstring=" include provider name too"  ></ConnectionStiring>

The best way I just found to address this is to temporarily set that project (most likely a class library) to the startup project. This forces the package manager console to use that project as it's config source. part of the reason it is set up this way is because of the top down model that th econfig files usually follow. The rule of thumb is that the project that is closest to the client (MVC application for instance) is the web.config or app.config that will be used.


It also happens if the startup project is changed to the one, which does not have the connection strings.

  1. Right Click Solution - click properties
  2. Under Common Properties,select startup project
  3. On the right pane select the project which has the connection strings (in most cases, it will be MVC projects - the project that starts the solution)

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?