I'm having a problem to handle the DB connection string in conjunction with migrations. I have 2 projects:
The DbContext
is in the Domain project, so this is the project I run migrations against. The migrations concept enforces me to implement OnConfiguring
in my DbContext
and therein specify the database provider, eg:
protected override void OnConfiguring(DbContextOptionsBuilder builder) { builder.UseSqlServer("<connection string>"); }
My problem is that I don't want to use a hard coded connection string, for obvious reasons, and I cannot use ConfigurationManager to read it from the config file since the config file is in the application project.
If you want to change the connection string go to the app. config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.
ASP.NET Core For instance, you can use the Secret Manager tool to store your database password and then, in scaffolding, use a connection string that simply consists of Name=<database-alias> . Or the following example shows the connection string stored in appsettings. json .
All the examples I've seen involve either hard-coding the connection string or putting it in my ASP.NET Core application's settings files.
If you aren't using ASP.NET Core, or maybe, I don't know, don't want to have your local environment's database details committed to source control, you can try using a temporary environment variable.
First, implement IDesignTimeDbContextFactory
like this (note that IDbContextFactory
is now deprecated):
public class AppContextFactory: IDesignTimeDbContextFactory<AppContext> { public AppContextFactory() { // A parameter-less constructor is required by the EF Core CLI tools. } public AppContext CreateDbContext(string[] args) { var connectionString = Environment.GetEnvironmentVariable("EFCORETOOLSDB"); if (string.IsNullOrEmpty(connectionString)) throw new InvalidOperationException("The connection string was not set " + "in the 'EFCORETOOLSDB' environment variable."); var options = new DbContextOptionsBuilder<AppContext>() .UseSqlServer(connectionString) .Options; return new AppContext(options); } }
Then, you can include the environment variable when you call Update-Database
, or any of the other EF Core tools:
$env:EFCORETOOLSDB = "Data Source=(local);Initial Catalog=ApplicationDb;Integrated Security=True"; Update-Database
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With