This folder contains infrastructure-related persistence logic such as Entity Framework Core’s DbContext, seeding logic and migrations.

DataContext

A DataContext (which is an alias for DbContext) class extends the DbContext class and provides the mappings between model entities and database tables, as well as other configuration functionalities; it may also contain DbSet properties.

DataSeed

A DataSeed class is responsible for seeding the database with initial values. It contains an Init method in which the seeding operation takes place. This method accepts an ISeeder instance which exposes a Seed method. This method will populate the database with a number of entities of any type which is mapped to a table.

Seeding can happen at migration-time or at startup-time.

TODO: Describe how to migrate at migration-time

Migrations

Migrations contain instructions to build and seed the database, and can be committed and rolled back. They are automatically generated by Entity Framework Core with the Add-Migration command.

How to migrate and seed the database at startup-time

Experimental feature: The seeding API is experimental. It may change in the next releases.

To ensure that the database is correctly migrated, you can use the Migrate method on the Database property of your data context. Then you can seed the database using the Seed extension method of the scope.

public static void Main(string[] args)
{
    IHost host = CreateHostBuilder(args).Build();

    using (IServiceScope scope = host.Services.CreateScope())
    {
        IServiceProvider services = scope.ServiceProvider;

        StoreDataContext context = services.GetRequiredService<StoreDataContext>();
        context.Database.Migrate();

        scope.Seed<StoreDataSeed>();
    }

    host.Run();
}