Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Seed Your Database With EF Core

DZone's Guide to

How to Seed Your Database With EF Core

Learn how to automate the data migration of your web application programmatically using Entity Framework Core and C# functions.

· Web Dev Zone ·
Free Resource

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Yesterday, I showed how to do EF Core DB migrations using either the Package Manager Console or the .NET CLI. But you can also do these code migrations automatically, triggering them via code.

After following the steps shown yesterday, you have all your migrations setup, and you can apply the DB changes using the dotnet CLI. But there is a lesser-known feature, that is still experimental and not ironed out completely, that makes it possible to run migrations from code, and even seed the DB with initial data.

Apply Migrations With Code

To just apply migrations you need to call the db.Database.Migrate() method, where db is the EF Context.

Typically, the following is the code needed to run the migration in code:

public static void Initialize(IServiceProvider service)
{
    using (var serviceScope = service.CreateScope())
    {
        var scopeServiceProvider = serviceScope.ServiceProvider;
        var db = scopeServiceProvider.GetService<TriathlonRaceTrackingContext>();
        db.Database.Migrate();
    }
}

This method can be called in the Configure method in the Startup class:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  ...
  Initialize(app.ApplicationServices);
}

Seeding the DB With Data

As part of the database initialization, you can also add some initial test data to the database. Unfortunately, it is not as automated as in Entity Framework 6, but can be coded manually.

For example, to add a new entry in the Race table, the code is as follows:

private static async Task InsertTestData(TriathlonRaceTrackingContext context)
{
    if(context.Races.Any())
        return;
    var race = new Race { Name="Ironman World Championship 2017",Location="Kona, Hawaii",Date=new DateTime(2017,10,14,7,0,0) };
    context.Add(race);
    await context.SaveChangesAsync();
}

The advantage of having to code it yourself is that you can decide if/when/how to seed the database. In this code, I just do it if the Race table is empty. But I could have decided to always wipe it clean, or anything else.

To include data seeding into the Initialize method, a few changes have to be made as the data seeding is an async method. So the Initialize becomes an InitializeAsync:

public static async Task InitializeAsync(IServiceProvider service)
{
    using (var serviceScope = service.CreateScope())
    {
        var scopeServiceProvider = serviceScope.ServiceProvider;
        var db = scopeServiceProvider.GetService<TriathlonRaceTrackingContext>();
        db.Database.Migrate();
        await InsertTestData(db);
    }
}

Also, the call from the Configure method must be slightly changed toInitializeAsync(app.ApplicationServices).Wait();.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

Topics:
web dev ,data migration ,entity framework ,web application data

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}