EF Core - Auto apply migrations with different SQL user

Viewed 120

I'm very new to .Net Core so please bear with me!

I'm working on a project that uses EF Core as a data provider. I have managed to set things up so that any outstanding migrations are applied when the applicaton starts by doing the following:

Snippet from program.cs:

    builder.Services.AddDbContext<MyDbContext>
       (options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

    builder.Services.AddTransient<IStartupFilter, MigrationStartupFilter<MyDbContext>>();

MigrationStartUpFilter.cs:

using Microsoft.EntityFrameworkCore;

public class MigrationStartupFilter<TContext> : IStartupFilter where TContext : DbContext
{
    public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
    {
        return app =>
        {
            using (var scope = app.ApplicationServices.CreateScope())
            {
                foreach (var context in scope.ServiceProvider.GetServices<TContext>())
                {
                    context.Database.SetCommandTimeout(160);
                    context.Database.Migrate();
                }
            }
            next(app);
        };
    }
}

This works fine, using the connection string from appSettings.json.

However - I do not want the SQL account that is used for general data access to have DDL permissions, what I'd like to do is have a different user with the correct privileges that I use just for the migrations.

Is this possible?

0 Answers
Related