How do you configure the DbContext when creating Migrations in Entity Framework Core?

后端 未结 7 1304
时光取名叫无心
时光取名叫无心 2020-12-11 02:51

Is there way that dependency injection can be configured/bootstrapped when using Entity Framework\'s migration commands?

Entity Framework Core supports dependency in

7条回答
  •  甜味超标
    2020-12-11 03:02

    As @bricelam commented this functionality does not yet exist in Entity Framework 7. This missing functionality is tracked by GitHub issue aspnet/EntityFramework#639

    In the mean time, the easier workaround I found was to utilize a global state rather than hassle with subclassing. Not usually my first design choice but it works well for now.

    In MyDbContext:

    public static bool isMigration = true;
    
    protected override void OnConfiguring( DbContextOptionsBuilder optionsBuilder )
    {
        // TODO: This is messy, but needed for migrations.
        // See https://github.com/aspnet/EntityFramework/issues/639
        if ( isMigration )
        {
            optionsBuilder.UseSqlServer( "" );
        }
    }
    

    In Startup.ConfigureServices().

    public IServiceProvider ConfigureServices( IServiceCollection services )
    {
        MyContext.isMigration = false;
    
        var configuration = new Configuration().AddJsonFile( "config.json" );
        services.AddEntityFramework( configuration )
            .AddSqlServer()
            .AddDbContext( config => config.UseSqlServer() );
        // ...
    }
    

    (The configuration code actually lives in an Autofac Module in my case.)

提交回复
热议问题