将构造函数注入IDesignTimeDbContextFactory

问题描述 投票:0回答:1

我试图在.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

entity-framework entity-framework-core
1个回答
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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.