How to seed your database with EF Core - Day 21 - 24 days of "Front-end Development with ASP.NET Core, Angular, and Bootstrap"

Yesterday I've shown how to do EF Core DB migrations using either the Package Manager Console or the dotnet 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 less-know feature, still experimental and not ironed out completely, that makes it possible to run migrations from code, and even seeding 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:

The advantage of having to code it yourself is that you can decide if/when/how to seed the database. In this 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 made as the data seeding is an async method. So the Initialize becomes an InitializeAsync: