Various seeds for development and production

What is the recommended approach to losing a database differently using Entity Framework (6+) depending on build configuration (Debug / Release)?

I am currently using the MigrateDatabaseToLatestVersion initializer. During development, I like to have fake data in my database for testing. Therefore, I create this test data in the Seed method of the Configuration class (which comes with the inclusion of the first code). However, every time I publish a product through the build server, I have to comment a lot of code inside my seed method, commit this, create a release, and then cancel all comments to continue development using test data.

I think this is not the way to go. So I hope you can tell me the right way to do this.

+4
source share
1 answer

there are many possibilities

  • Preprocessor directive

One of you, like Geert Arnold, has already spoken using #if DEBUG:

protected override void Seed(BookService.Models.BookServiceContext context)
{
#if DEBUG
    context.Authors.AddOrUpdate(x => x.Id,
        new Author() { Id = 1, Name = "Test User" },
    );
#else
    context.Authors.AddOrUpdate(x => x.Id,
        new Author() { Id = 1, Name = "Productive User" },
    );
#endif
}
  1. Configuration

Another way is with customization in appsettings.json, maybe you want to customize the application using development data, you can add something like

{ "environment" : "development" }

and in the seed you check this:

protected override void Seed(BookService.Models.BookServiceContext context)
{
    var builder = new ConfigurationBuilder();
    builder.AddInMemoryCollection();
    var config = builder.Build();

    if (config["environment"].Equals("development"))
    {
        context.Authors.AddOrUpdate(x => x.Id,
            new Author() { Id = 1, Name = "Test User" },
        );
    }
    else if (config["environment"].Equals("producion"))
    {
        context.Authors.AddOrUpdate(x => x.Id,
            new Author() { Id = 1, Name = "Productive User" },
        );
    }
}
  1. Environment variables (solution for asp net core )

(see also https://docs.asp.net/en/latest/fundamentals/environments.html )

You can add an environment variable

enter image description here and later through DI:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        SeedDataForDevelopment();
    }
}
+5
source

Source: https://habr.com/ru/post/1652383/


All Articles