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

后端 未结 7 1284
时光取名叫无心
时光取名叫无心 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:11

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

    public class FooDbContextFactory : IDesignTimeDbContextFactory
    {
        public FooDbContext CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    
            var builder = new DbContextOptionsBuilder();
            var connectionString = configuration.GetConnectionString("ConnectionStringName");
            builder.UseSqlServer(connectionString);
    
            return new FooDbContext(builder.Options);
        }
    }
    

提交回复
热议问题