Miguel Moura
Miguel Moura

Reputation: 39464

Add Test Data when creating migrations

I have the following Entity Framework Core 2.1 entity configuration:

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

    });

  }
}

When working on the project I would like to run migrations on Development environment.

So in this case I would like to add more than 4 categories ...

But before publishing the project to production I would like to run migrations on Production environment and add only the 4 categories of my example.

So I need to set a variable, when running migrations, that determines if live or test data is inserted into the database.

Is this possible? How can is this usually done?

Upvotes: 1

Views: 262

Answers (1)

VahiD
VahiD

Reputation: 1064

in your Up method of migration, you can check for the Database name, and decide what to do based on your desired database. for example you can run a SqlQuery to insert the rows you want.

for getting database name you can use below code:

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

Upvotes: 0

Related Questions