Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Entity framework 创建迁移时添加测试数据_Entity Framework_Entity Framework Core - Fatal编程技术网

Entity framework 创建迁移时添加测试数据

Entity framework 创建迁移时添加测试数据,entity-framework,entity-framework-core,Entity Framework,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 =&

我有以下实体框架核心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" }
      );         

    });

  }
}
公共类类别配置:IEntityTypeConfiguration{
公共void配置(EntityTypeBuilder){
builder.With(x=>{
x、 ToTable(“类别”);
x、 属性(y=>y.Id);
x、 属性(y=>y.Name).IsRequired(true).HasMaxLength(40);
x、 HasData(
新的{Id=1,Name=“A”},
新的{Id=2,Name=“B”},
新的{Id=3,Name=“C”},
新的{Id=4,Name=“D”}
);         
});
}
}
在项目中工作时,我希望在开发环境中运行迁移

所以在这种情况下,我想增加4个以上的类别

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

因此,在运行迁移时,我需要设置一个变量,该变量确定是将实时数据还是测试数据插入数据库


这可能吗?这通常是如何实现的?

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