Applying Seed Data To The Database

Unlike in previous versions of Entity Framework, there is currently no formal method for applying seed data to the database in Entity Framework Core. This feature should be added to EF Core 2.1 and is being tracked here: https://github.com/aspnet/EntityFrameworkCore/issues/629.

In the meantime, the advice is to create code for adding the seed data and then to call that code in application startup.

The following code illustrates this pattern, seeding the database with countries:

public class DataSeeder
{
    public async static Task SeedCountries(DbContext context)
    {
        if (!context.Countries.Any())
        {
            var countries = new List<Country>
            {
				new Country { Name = "Afghanistan" },
				new Country { Name = "Albania" },
				new Country { Name = "Algeria" },
				new Country { Name = "Andorra" },
				new Country { Name = "Angola" },
				new Country { Name = "Antigua and Barbuda" },
				new Country { Name = "Argentina" },
				new Country { Name = "Armenia" },
				new Country { Name = "Aruba" },
				new Country { Name = "Australia" },
				new Country { Name = "Austria" },
				new Country { Name = "Azerbaijan" },
                ...
            };
            context.AddRange(countries);
            await context.SaveChangesAsync();
        }
    }
}

While this example uses hardcoded country names (and is curtailed for brevity), the code could just as simply read seed data from an external file such as a web service, text or XML file.

The SeedCountries method is called in the Configure method of the Startup class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
        DataSeeder.SeedCountries(context).Wait();
    }
	...
}

Created:
Last updated: 02/11/2017 10:24:36
Proficiency Level: Beginner