我试图在.NET标准2.0类库中使用迁移EFCore2.0,到目前为止我有类似的东西
public class SomeContextFactory : IDesignTimeDbContextFactory<SomeContext>
{
private Configuration _configuration;
public SomeContextFactory(Configuration configuration)
{
_configuration = configuration;
}
public SomeContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<SomeContext>();
optionsBuilder.UseSqlServer(_configuration.ConnectionString);
return new SomeContext(optionsBuilder.Options);
}
}
public class SomeContext : DbContext
{
public DbSet<SomeDbModel> Some { get; set; }
public SomeContext(DbContextOptions<SomeContext> options) : base(options)
{
}
}
关键是连接字符串根据环境(dev,test,prod)而不同,并且应该在Configuration
指定的数据库上执行迁移。
如何指示迁移将Configuration
注入SomeContextFactory
?
在Startup.cs中
services.AddTransient<SomeContextFactory>();
而你的工厂:
public class SomeContextFactory :
IDesignTimeDbContextFactory<SomeContext>
{
private readonly IHostingEnvironment environment;
private readonly IConfigurationRoot config;
public SomeContextFactory(IConfigurationRoot config,
IHostingEnvironment environment)
{
this.environment = environment;
this.config = config;
}
public SomeContext CreateDbContext()
{
return CreateDbContext(null);
}
public SomeContext CreateDbContext(string[] args)
{
var builder = new DbContextOptionsBuilder<SomeContext>();
var connectionString = config.GetConnectionString("Default");
builder.UseSqlServer(connectionString);
return new SomeContext(builder.Options);
}
}