2017-10-05 39 views
0

我試圖使用遷移EFCore2.0在.NET 2.0的標準類,到目前爲止,我有這樣的事情構造注入IDesignTimeDbContextFactory

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

回答

0

在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); 
    } 
}