269

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?

Green Falcon
  • 818
  • 3
  • 17
  • 48
jjc99
  • 3,559
  • 4
  • 22
  • 21
  • 16
    Not exactly the same context as yours (automatic migrations with EF6) but I had the same problem with similar error message when I created a child branch on TFS and began working on it. Marking the mvc project as start-up project resolved this. **output** `PM> Update-Database -Verbose Using StartUp project 'xxxxx.Web.Home'. Using NuGet project 'xxxxx.Web.Home.Dal'. Specify the '-Verbose' flag to view the SQL statements being applied to the target database. Target database is: 'MovieDatabase-0.0.2' (DataSource: (LocalDb)\v11.0, Provider: System.Data.SqlClient, Origin: Configuration).` – Mechanical Object Feb 02 '14 at 17:36

28 Answers28

328

Try copying the connections string to the .config file in the MVC project.

Jerry
  • 6,357
  • 8
  • 35
  • 50
  • 65
    Works perfect but would love to know why the referenced project is not using its own config file to fetch the connection string. – Null Head Jan 21 '13 at 09:40
  • 1
    I had to add it to my web.config for the MVC project, app.config there was not loaded. Not sure why it is looking there for a separate project. – Chris Ballance Jan 08 '14 at 19:47
  • 22
    @Alexander, the framework loads and uses the configuration file(s) for the executing assembly. In this case, it's the web project. Class libraries generally don't have their own configuration files. – kiprainey Mar 20 '14 at 17:21
  • 26
    The Enable-Migration commands when run in the context of the NuGet COnsole, looks at the Startup Projects config file, not necessarily the project you would think it would be in. Just set the project with the app.config you want to be the startup project. Optionally, Store your connection strings in one config file, then reference them in other projects by – Ryan Mann Jun 16 '14 at 22:20
  • 3
    I got this exact error message, but my .config file - in the right project - indeed listed the correct connection-string. However, I was using transformations, and the connection-string was of course not referenced in the transformed .config-file. So that's something to look out for, if you're using config-file transformations. – Morten Nørgaard Feb 05 '15 at 22:24
  • 1
    How is that not a bug? Anyway; sorted my issue all the same. – Dave Lawrence Jul 10 '15 at 12:35
  • 1
    not very intuitive. surely there must be a fix for this in the coming versions. i just wasted a day. wouldnt have guessed. why have the app.config if my class library wont use it. Thanks @Jerry – defcde Jan 14 '16 at 07:31
  • 1
    The configuration file loaded/used is always the one from the project that starts the process. In this case, the "container" MVC project is the one that owns the process, so the configuration file loaded (by default) will be its .config file. – Fabricio May 17 '17 at 16:59
  • @RyanMann unfortunately `configSource` cant reference a file in a parent or sibling folder. It give the exception: `ArgumentException: The configSource '..\\Web.config' is invalid. It must refer to a file in the same directory or in a subdirectory as the configuration file.` – br3nt Oct 10 '19 at 00:31
  • Anyone following @RyanMann's suggestion, look at [this answer](https://stackoverflow.com/a/40450836/848668) which has a really great step by step guide on sharing connection strings among multiple projects in a solution! – br3nt Oct 10 '19 at 00:56
157

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

Community
  • 1
  • 1
Oren
  • 2,462
  • 3
  • 18
  • 16
  • 8
    The key answer to this is that the class library (where the .edmx file is) is not your STARTUP project. I realised that my startup project wasn't set to the project that had my web.config in. It was a console app with a different app.config. So if you're adding console applications to your web solution, make sure your web project is the startup project when you run update-database! – Karl Jun 11 '13 at 12:27
  • 1
    I have unloaded my main project for some reason and after reloading it I got this error trying to add migrations. Making the main project startup project again solved the issue. Thanks @Oren – Azadrum Oct 13 '14 at 14:04
  • 2
    My startup project had been changed by mistake. That's the key bit. Your answer really helped! – Fabio Milheiro Apr 19 '15 at 18:13
110

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

CMS
  • 3,657
  • 1
  • 27
  • 46
  • 4
    It's actually the project contains the connection string should be set as startup project, and usually it's not the project that your DbContext file sits – Raymond Wang May 25 '16 at 17:17
  • I like this answer the best. In our solutions, we put `app.config` files in many of our non-executable layers, in spite of the fact that a non-exe can't directly utilize a config file. Depending on the targeted .exe, it can help inform the developer what he needs to copy/paste in order to compose the desired application's `app.config` – bkwdesign Oct 06 '16 at 16:06
  • 1
    ... thus, in addition to making sure the Package Mgr targets the right layer, that very same layer needs to be `Set as Startup Project` - as per the screenshot shown above. (even though if you hit F5, you wouldn't be able to start the class library) – bkwdesign Oct 06 '16 at 16:20
  • 3
    This saved my life. Even though in the Package Manager I had the Default Project set to the project where the context was set, it still didnt override. – garfbradaz Apr 24 '17 at 14:12
  • 1
    "But it worked yesterday! The *exact same command*!" => THIS! – Simon_Weaver Feb 27 '18 at 23:22
35

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...
}
Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
  • and made my day as well because I couldn't find a solution to why my startup project suddenly stopped finding the config file. My app.config and .exe.config was showing up in my startup project bin and yet EntityFramework couldn't find the connection string that I had been using forever. I did remove a number of unused projects recently from the solution and I'm wondering if that had anything to do with it. I did remove a web project from the solution. Wondering if my other projects were relying on the web.config or something unusual like that. – GrayDwarf May 09 '17 at 14:29
  • The config of the running project is used by all other child projects. – Serj Sagan May 09 '17 at 20:22
  • 3
    but how to set provider name? – FizxMike Aug 10 '17 at 14:57
10

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.

Ravi Anand
  • 5,106
  • 9
  • 47
  • 77
9

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

podiluska
  • 50,950
  • 7
  • 98
  • 104
8

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

Marek Woźniak
  • 1,766
  • 16
  • 34
7
  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>
    
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
5

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Def Type
  • 51
  • 1
  • 1
4

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)
Ravi Ganesan
  • 277
  • 6
  • 11
3

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)
Chalky
  • 1,624
  • 18
  • 20
2

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

Diego
  • 34,802
  • 21
  • 91
  • 134
  • Yes, this is the case. The project that contain the connection string is a class library which includes only an App.config file. The MVC project does not seem to be checking this tho. – jjc99 Sep 27 '12 at 14:16
  • during the development it will only chech the app.config on its project, you must add there – Diego Sep 27 '12 at 15:24
  • Thanks for you're reply. I've tried copying the connection string from the project containing the edmx file and placing it in the root web.config file in my MVC project. Unfortunately, it still can't find the connection string. Do I have to modify the connection string in any way? – jjc99 Sep 27 '12 at 15:35
  • its the other way around. In dev time you need the con string on the app.cofnig on the Project that has the .edmx file. If you have it maybe the name is wrong. The name of the connections string should be the same name as the "entity containr name" property of your .edmx file – Diego Sep 28 '12 at 08:17
1

Add ConnectionString to MVC Project Web.config file

Mamedov
  • 449
  • 4
  • 3
1

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
ch2o
  • 815
  • 2
  • 12
  • 29
1

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.

Niraj Trivedi
  • 2,370
  • 22
  • 24
  • 1
    Thanks, I had a problem with my project loading and it lost the "Startup Project". Your answer reminded me to make sure the project with the Context file and app.config was the Startup. – Mastro Aug 06 '17 at 17:13
1

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.

JakeJ
  • 2,361
  • 5
  • 23
  • 35
  • This way you can include the commands in your procedures and not have to constantly change the startup project away from the default. – JakeJ Mar 06 '19 at 22:05
0

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.

Mike Beeler
  • 4,081
  • 2
  • 29
  • 44
0

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.

gcoleman0828
  • 1,541
  • 3
  • 30
  • 49
0

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 :)

ShayLivyatan
  • 103
  • 7
0

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.

Debendra Dash
  • 5,334
  • 46
  • 38
0

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

Pawan Rai
  • 21
  • 2
0

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.

Brian Wirt
  • 142
  • 3
  • 9
0

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"

therightstuff
  • 833
  • 1
  • 16
  • 21
0

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.

sm2mafaz
  • 392
  • 3
  • 15
0

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.

br3nt
  • 9,017
  • 3
  • 42
  • 63
0

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.

midohioboarder
  • 438
  • 5
  • 14
0

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 :)

Adam
  • 309
  • 3
  • 8
-1

Add Connectoinstrnig in web.config file

<ConnectionStiring> <add name="dbName" Connectionstring=" include provider name too"  ></ConnectionStiring>
saun4frsh
  • 383
  • 1
  • 4
  • 21