【问题标题】:Add Test Data when creating migrations创建迁移时添加测试数据
【发布时间】:2018-10-21 20:57:24
【问题描述】:

我有以下 Entity Framework Core 2.1 实体配置:

public class CategoryConfiguration : IEntityTypeConfiguration<Category> {

  public void Configure(EntityTypeBuilder<Category> builder) {

    builder.With(x => { 
      x.ToTable("Categories");
      x.Property(y => y.Id).UseSqlServerIdentityColumn();  
      x.Property(y => y.Name).IsRequired(true).HasMaxLength(40);

      x.HasData(
        new { Id = 1, Name = "A" },
        new { Id = 2, Name = "B" },
        new { Id = 3, Name = "C" },
        new { Id = 4, Name = "D" }
      );         

    });

  }
}

在开发项目时,我想在开发环境中运行迁移。

所以在这种情况下,我想添加超过 4 个类别...

但在将项目发布到生产环境之前,我想在生产环境中运行迁移并仅添加我示例的 4 个类别。

所以我需要在运行迁移时设置一个变量,以确定是否将实时数据或测试数据插入到数据库中。

这可能吗?这通常是怎么做到的?

【问题讨论】:

    标签: entity-framework entity-framework-core


    【解决方案1】:

    在您的 Up 迁移方法中,您可以检查数据库名称,并根据您所需的数据库决定要做什么。例如,您可以运行 SqlQuery 来插入所需的行。

    要获取数据库名称,您可以使用以下代码:

    public override void Up()
    {   
        var builder = new System.Data.SqlClient
             .SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString);
        var dbname = builder.DataSource;
        if (dbname == "dbLive")
        {
            Sql("insert into table1 values('A' , 'B')");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      相关资源
      最近更新 更多