Menu

Migrations and Seeding on ASP.NET Core

Since most of us using the CodeFirst (Love it!!! – makes our lives easy), its necessary to have the migration executed before it all begins. Since ASP.NET Core is pretty new (at the time I am writing the code), it necessary to have every thing set up correctly from the beginning.

Create a class called DbInitializer.cs, below is the code.

public static class DbInitializer
{
    public static void Initialize(ActivitiesContext context)
    {
        context.Database.EnsureCreated();
        context.Database.Migrate();

        if (CheckAlreadySeeded(context))
            return;

        SeedQuestionTypes(context);        
    }

    private static bool CheckAlreadySeeded(QuestionContext context)
    {
        if (context.QuestionTypes.Any())
        {
            return true;
        }
        return false;
    }

    private static void SeedQuestionTypes(QuestionContext context)
    {
        var questionTypes= new[]
        {
            new QuestionType { QuestionType Id = 1, Name = "Daily"},
            ....
            ....
        };
        context.QuestionTypes.AddRange(questionTypes);
        context.SaveChanges();
    }
   
}

On the Startup.cs, under Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, QuestionContext context)
{            
   app.UseExceptionHandler("/Home/Error");
           
   app.UseStaticFiles();
             
   app.UseMvc();

   DbInitializer.Initialize(context);
}

 

Leave a comment