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

后端 未结 7 1285
时光取名叫无心
时光取名叫无心 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( "<Your Connection String Here>" );
        }
    }
    

    In Startup.ConfigureServices().

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

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

    0 讨论(0)
  • 2020-12-11 03:03

    I know this is a old question but I use the onConfiguring method and I don't have this problem

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
    }
    
    0 讨论(0)
  • 2020-12-11 03:10

    I just ask for an instance and run migrations in my Startup.cs file

      public void ConfigureServices(IServiceCollection services)
        {
            // ASPNet Core Identity
            services.AddDbContext<RRIdentityDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("RRIdentityConnectionString")));
    
         }
    

    And then in Configure:

       public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var rrIdentityContext = app.ApplicationServices.GetService<RRIdentityDbContext>();
            rrIdentityContext.Database.Migrate();
        }
    

    Note: There is no 'EnsureCreated' for the database. Migrate is supposed to create it if it doesn't exist, although how it is supposed to figure out the permissions I don't know - so I created an empty database.

    0 讨论(0)
  • 2020-12-11 03:11

    In .NET Core since version 2.1 should be used IDesignTimeDbContextFactory because IDbContextFactory is obsolete.

    public class FooDbContextFactory : IDesignTimeDbContextFactory<FooDbContext>
    {
        public FooDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    
            var builder = new DbContextOptionsBuilder<FooDbContext>();
            var connectionString = configuration.GetConnectionString("ConnectionStringName");
            builder.UseSqlServer(connectionString);
    
            return new FooDbContext(builder.Options);
        }
    }
    
    0 讨论(0)
  • 2020-12-11 03:12

    If you are looking for a solution to configure cotext for imgrations, you can use this in you DBContext class:

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
                var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
                optionsBuilder.UseSqlServer(connectionString);
            }
        }
    

    Remember to install those two packages to have SetBasePath and AddJsonFile methods: Microsoft.Extensions.Configuration.FileExtensions

    Microsoft.Extensions.Configuration.Json

    0 讨论(0)
  • 2020-12-11 03:18

    To combine the answers above this works for me

    private readonly bool isMigration = false;
    public MyContext()
    {
        isMigration = true;
    }
    
    public MyContext(DbContextOptions<MyContext> options) : base(options)
    {
    
    }
    
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (isMigration)
        {
            optionsBuilder.UseSqlServer("CONNECTION_STRING");
        }
    }
    
    0 讨论(0)
提交回复
热议问题