Creating and using a database can be done by adding the following lines to the components sections of the microservice’s yml file.

components:
  ...

  - name: sqlserver
    type: database
    provider: sqlserver

  ...

This will generate a container which will host an instance of a SqlServer database, which will be dedicated to that one microservice that requested it.

docker-compose.yml:

services:
  ...

  sqlserver:
    image: mcr.microsoft.com/mssql/server:2019-latest

  ...

docker-compose.override.yml:

services:
  ...

  sqlserver:
    environment:
      - SA_PASSWORD=Password1
      - ACCEPT_EULA=Y
    ports:
      - 5433:1433
    volumes:
      - sqlservervolume:/var/opt/mssql

  ...

Of course, you will want to override the predefined environment variables, ports and volumes in production.

This action also generates a couple of lines in the microservice project that will integrate the newly added SqlServer component into the microservice using EntityFramework Core.

Startup.cs:

services.AddDbContext<StoreDataContext>(opt => opt.UseSqlServer(Configuration["ConnectionString"]));

Program.cs:

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

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

    scope.Seed<StoreDataSeed>();
}

You can use the DbContext class (here, StoreDataContext) to configure EntityFramework Core’s settings, and the seed class (here, StoreDataSeed) to seed the database.

Once you registered some entities, create a migration. This can be used to create or update the database at startup time. To create a migration, select your microservice project as startup project. Then, make sure to include a ConnectionString section in the appsettings.json file; this step is necessary because EntityFramework Core needs a connection string to create an instance of the DbContext. Include this section anywhere in the json file:

{
    "ConnectionString": "Server=sqlserver;Database=couriers_db;User Id=sa;Password=Password1"
}

you can delete it once the migration is created. Then, open the Package Manager Console and run:

Add-Migration Initial -o Infrastructure/Data/Migrations

We recommend to add your migrations under the Infrastructure/Data/Migrations folder.

Once the application starts, the migration will be applied to the database; if the database does not exists, it will be created.

Now, you can also use the autogenerated repositories in your project!