Search code examples
c#asp.net-core.net-coreentity-framework-coreentity-framework-migrations

Command line connection string for EF core database update


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.


Solution

  • 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