Code First Microservices With a Single Database in Entity Framework Core

December 21, 2021

All of your microservices would have their own database in the ideal universe. Unfortunately, enterprise development is not in the ideal universe. When provisioning databases is complicated, you often get stuck with a single database per environment. If you want to work around this constraint and maintain some semblance of data separation, you can use schemas to separate your services. In this post, you’ll learn how to use a single database to support multiple instances of EF Core.

Here’s how to do it.

First, override OnModelCreating and add a call to HasDefaultSchema() in your DbContext setup. This code sets all of the tables for your database to your chosen schema.

public const string  SCHEMA = "character";

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDefaultSchema(SCHEMA);
}

Then, in your DbContext setup in Program.cs (or Startup.cs), add a call to MigrationsHistoryTable() in your services setup. This code will set the migration table to the one you specify, including the schema.

builder.Services.AddDbContext<AppDbContext>(options =>
  options.UseSqlServer(builder.Configuration.GetConnectionString("db"), 
                       x=> x.MigrationsHistoryTable("__EfMigrations", AppDbContext.SCHEMA)));

From here, you can continue to use Entity Framework Core as you usually would. Everything should appear in your chosen schema. Rinse and repeat for each of your services.

Tables

You can customize your migrations with EF Core, so each service has its own migration table. While this isn’t ideal, it’ll tide you over until you can move to the cloud or get more databases.


Dustin Ewers

Written by Dustin Ewers who lives and works in Southern Wisconsin. GitHub | Twitter | LinkedIn


© 2022, Built by Dustin Ewers with Gatsby
Disclaimer

The posts on this site are my own and don’t necessarily represent my employer's positions, strategies, or opinions.

Some of the links contained within this site have my referral ID, which provides me with a small commission for each sale. Thank you for your support.