Reputation: 67315
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.
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?
Upvotes: 5
Views: 2450
Reputation: 13
I was wondering which appsettings.json would the application use if i used Package Manager Console from Visual Studio 2022. I had appsettings.json
, appsettings.Development.json
and appsettings.Production.json
, each with different connection string.
The one used was appsettings.Development.json
.
Upvotes: 0
Reputation: 1270
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.
Upvotes: 4