实体框架核心迁移自定义历史记录表列

时间:2018-08-22 16:57:28

标签: entity-framework-core ef-migrations

我试图弄清楚如何在“迁移历史记录”表中添加和设置自定义列的值。我想出了如何使用这样的自定义SqlServerHistoryRepository添加列:

class MyHistoryRepository : SqlServerHistoryRepository
{
    public MyHistoryRepository(HistoryRepositoryDependencies dependencies) : base(dependencies)
    {            
    }

    protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)
    {
        base.ConfigureTable(history);
        history.Property<DateTime>("Applied").HasDefaultValue(DateTime.Now);
        history.Property<string>("UserStamp");
    }
}`

我正在针对.NET Standard的库中创建数据层。我为看起来像这样的迁移创建了一个IDesignTimeDbContextFactory。

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyContext>
{
    public MyContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
        optionsBuilder.UseSqlServer("connectionString",
            ob => ob.MigrationsAssembly(this.GetType().Assembly.GetName().Name))
            .ReplaceService<IHistoryRepository, MyHistoryRepository>();

        return new MyContext(optionsBuilder.Options);
    }
}

如何将UserStamp的值传递到迁移历史记录表中?

1 个答案:

答案 0 :(得分:0)

您可以使用依赖项注入将任何服务直接传递到IHistoryRepository的实现中。

例如,要从文件中读取值,您可以执行以下操作:

public class MyHistoryRepository : NpgsqlHistoryRepository
{
    private readonly IConfiguration _config;

    public MyHistoryRepository(
        HistoryRepositoryDependencies dependencies,
        IConfiguration config) : base(dependencies)
    {
        _config = config;
    }

    protected override void ConfigureTable(EntityTypeBuilder<HistoryRow> history)
    {
        base.ConfigureTable(history);
        history.Property<DateTime>("Applied").HasDefaultValue(DateTime.Now);
        history.Property<string>("UserStamp")
            .HasDefaultValue(_config["UserStamp"] ?? "");
    }
}

public class MyDbContextFactory : IDesignTimeDbContextFactory<MyContext>
{
    public MyContext CreateDbContext(string[] args)
    {
        var services = new ServiceCollection();

        IConfiguration config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json")
            .Build();

        // in your case this would probably be 'AddEntityFrameworkSqlServer'
        services.AddEntityFrameworkNpgsql();
        services.AddSingleton<IConfiguration>(config);
        services.AddScoped<IHistoryRepository, MyHistoryRepository>();

        var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
        optionsBuilder.UseNpgsql(config.GetConnectionString("DefaultConnection"))
            .UseInternalServiceProvider(services.BuildServiceProvider());

        return new MyContext(optionsBuilder.Options);
    }
}