Using ASP.NET Core and EF Core, I am trying to apply migrations to the database. However, the login in the connection string in appsettings.json
that the app will use has only CRUD access, because of security concerns, so it can't create tables and columns, etc. So, when I run:
dotnet ef database update -c MyDbContextName -e Development
I want to tell it to use a different connection string, but I don't know if this can be done? Basically, I want to use two different connection strings, one for deployment and one for running the app. Is this possible? Is there a better approach? Thanks.
Keep both connection strings in appsettings.json
. Inherit a child context class from the main one and override OnConfiguring
with another connection string:
public class ScaffoldContext : MyDbContextName
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string scaffoldConnStr = ConfigurationManager.ConnectionStrings["scaffoldConnStr"].ConnectionString;
optionsBuilder.UseSqlServer(scaffoldConnStr);
}
}
Then use:
dotnet ef database update -c ScaffoldContext
I liked the idea of a scaffolding DbContext, but I found some issues (somehow solvable, I guess) and also some consideration on where to keep connection strings. Those led me to another, more crude solution, so I thought I'd share all that here.
This is about the general approach, and consequent solution:
MyDbContextName
, instead of adding a new one. Thus the whole scaffolding DB context thing could be overcome doing this way.Other issues I found along the way:
Initial DbContext had dependencies injected into constructor, so child context had to to the same. This made dotnet ef
commands complain about missing parameterless constructor.
To overcome that, child context as well was registered at startup with .AddDbContext<ChildDbContext>(...)
. This also required for ChildDbContext to be injected both with a DbContextOptions<ParentDbContext>
as well as a DbContextOptions<ChildDbContext>
. After that, dotnet-ef
still found issues with instantiating ChildDbContext, as that needed also a dependency on IConfiguration
which could not be found. Maybe (?) this is due to the fact that dotnet-ef
does not run through the whole application startup.
As I said, I guess the issues could be solved after all, but still I'm questioning the real value of a scaffolding context in case you don't want to save connection strings in dedicated appsettings files. One counter argument could be that you might forget the environment variable set to the remote connection string, but then you just have to close the command window as soon as you complete migration. HTH