9

I'm using the new way of seeding data in EF Core 2.1 and I want to seed data for the development environment only.

Initially I tried this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") != EnvironmentName.Development)
    {
        return;
    }

    modelBuilder.Entity<Customer>().HasData(new Customer { ... });
}

However, I noticed that the generated migration will always insert the customers into the database.

Is there a way of restricting the data seed on a per environment basis?

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
ChaoticNadirs
  • 2,280
  • 2
  • 20
  • 27
  • Is this seeding data or creating tables? – Vivek Nuna Jun 25 '18 at 15:15
  • @viveknuna this is seeding data. Tables should be created for all environments. Seed data should only be added for development environment. – ChaoticNadirs Jun 25 '18 at 15:18
  • @ChaoticNadirs did you find any good solution yet? – ibubi Dec 28 '18 at 05:07
  • Your solution works if you set the ASPNETCORE_ENVIRONMENT per [this](https://stackoverflow.com/questions/45881069/ef-core-doesnt-use-aspnetcore-environment-during-update-database) other SO article – doveryai Feb 01 '22 at 20:56

2 Answers2

2

This is a bit old, but what I did was create extension methods to call from Startup.cs and based on if the database exists, seed it or not. I also wrapped that call in an env The seeding of the db won't happen if the database already exists, however, I believe this behavior is fine, because of the database already exists you are most likely not in a dev environment.

public static class Extensions
{
    public static void UseDbSeeding(this IApplicationBuilder app)
    {
        var factory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();
        using var serviceScope = factory.CreateScope();
        var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
        if(context.Database.EnsureCreated()) // false when db already exists
        {
            // Seed here
            context.SaveChanges();
        }
    }
}

And from Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
{
    if (env.IsDevelopment())
    {
        app.UseDbSeeding();
    }
}
sebsmgzz
  • 361
  • 2
  • 11
-1

I think you can do in Startup.cs in ConfigureServices method like this

if (env.IsDevelopment())
   // then seed data

Here is recommended way to seed data in Asp.Net Core (Note that I'm not checking environment here). Please look at my sample here

And this file will be use to at run time seed

Community
  • 1
  • 1