Seed database in ASP.NET Core

December 04, 2017 by Anuraj

ASP.NET Core EF Core

This post is about how to seed database in ASP.NET Core. You may want to seed the database with initial users for various reasons. You may want default users and roles added as part of the application. In this post, we will take a look at how to  seed the database with default data.

First you need to create a static class, SeedData with Initialize method. The class name and method name can be anything. You need to write the code to check whether Database is created or not. If it is created, write the EF Code to insert the data. Here is some pseudo code for the same.

public static class SeedData
    public static void Initialize(IServiceProvider serviceProvider)
        var context = serviceProvider.GetRequiredService<WebMarksDbContext>();
        if (!context.Tenants.Any())
            context.Tenants.Add(new Tenant() { Name = "Hello", Host = "hello", Style = "red.css" });
            context.Tenants.Add(new Tenant() { Name = "Sample", Host = "sample", Style = "blue.css" });

Next you need to invoke the Initialize method. In ASP.NET Core 1.0, the recommended approach is calling it from Configure method in Startup class.

app.UseMvc(routes =>
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");


And in ASP.NET Core 2.0, the recommended approach is invoking it from main method in program class.

public static void Main(string[] args)
    var host = BuildWebHost(args);

    using (var scope = host.Services.CreateScope())
        var services = scope.ServiceProvider;
        var context = services.GetRequiredService<WebMarksDbContext>();
        catch (Exception ex)
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred seeding the DB.");


Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub