Where Does Entity Framework 6 Get Connection String For Migrations?

ef-code-first entity-framework entity-framework-6 visual-studio


I'm using EntityFramework 6 code first with migrations. I have two projects -- UI and BusinessLogic. UI is a .NET MVC web application with a dependency on BusinessLogic, which is a class library. WebUI has the config section including connection string. BusinessLogic also has the following config section (with no connection strings provided) and contains the actual code first Migration classes:

<entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>

In Package Manager Console when I run update-database -ProjectName BusinessLogic it somehow knows to use the connection string from my UI project.

In an attempt to understand how/why this was happening, I attached the debugger to the constructor of my DbContext class like this:

public MyDbContext() : base(CloudConfigurationManager.GetSetting(CONNECTION_STRING_KEY, false))
  //--launch the debugger

Now with the debugger launched and a breakpoint in the DbContext constructor, I can evaluate AppDomain.CurrentDomain.BaseDirectory which yields:

C:\\someRepoLocation\\Source\\BusinessLogic\\bin\\Debug\\ This seems to indicate that the current app domain is BusinessLogic.

However, evaluating AppDomain.CurrentDomain.SetupInformation.ConfigurationFile yields: C:\\someRepoLocation\\Source\\UI\\tmpD442.tmp

So the current app domain is BusinessLogic, but it is using some .tmp configuration file in the root UI folder? Wat?

Can anyone explain how/why this works without having a connection string providing in the app.config of BusinessLogic (where the Migrations exist)? I was expecting I'd have to set a connection string in the BusinessLogic class library's app.config -- but I'm happy not to do this if this is the expected behavior. Looking forward to hear what is the explanation!

1/31/2018 2:46:35 AM

Accepted Answer

Through some testing of my own, I've discovered that the config that is used during an update-database call is the currently set start-up project.

In my case, I set up a console application to do some batch work, and while debugging through the seed, I noticed the same behavior as you noted. Swapping the start up project is what changes the active configuration.

3/8/2018 3:14:51 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow