How does Package Manager Console know which connection string to use?

Viewed 654

I have a website application. Depending on the IsDemoSite setting in my appsettings.json file, the application uses one of two different database connection strings. (One for my main site, and another for our demo site.)

I also have a class library that contains all the Entity Framework models and migrations.

In the Package Manager Console, I set the Default project to the class library.

Default project setting in Package Manager Console

Then, I can run the add-migration and update-database commands on that class library. But here's the kicker: The IsDemoSite setting for my main application determines which database these commands work with.

How on Earth does Package Manager Console know to what connection string is used by my main application based on the current setting? I'm not running the main application. Package Manager Console is not using the main application as the default project. How the heck does it know which connection string to use?

1 Answers

When you run and add-migration or an update-database command, Package Manager Console will look for the Startup project of your solution and use it as "entry point" for these commands.

Probably inside your Startup.cs class you have the database context injected using the connection string that is stored in your appsettings.json.

I believe you have something like that:

string connectionString;

bool isDemoSite = configuration.GetValue<string>("IsDemoSite");

if(isDemoSite)
    connectionString = configuration.GetConnectionString("mainSite");
else
    connectionString = configuration.GetConnectionString("demoSite");

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

add-migration and update-database uses this very same code to determinate against which database it will execute, is something like your application is beign executed to allow this commands to run.

That's also the reason you need some EntityFramework packages installed in your startup project.

Related