Before you read this article, I advise you to read the first part
Sometimes some developer needs multiple contexts of our project. This is a little different than a single context. Multiple contexts mean multiple database context. That means is direct to the constructor. In this project, I need authentication and JWT token implementation. So I would like to use Microsoft Identity Server Document and I want to store a registered user in a database. Here is the problem I need a new context without CommunityContext. But how? At the same time, I ask myself what is the migration commands for every context. Let me explain.
Create new context and call "AppIdentityDbContext". Every single context include own options like DbContextOptions
using Core.Entities.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure.Identity
{
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options) :
base(options)
{
}
}
}
AppUser.cs
public string DisplayName { get; set; }
public bool IsActive { get; set; }
public bool IsWantToAuthor { get; set; }
public bool IsAuthor { get; set; }
public UserType UserType { get; set; }
Here is the second database context DbContextOptions options
using Core.Entities;
using Core.Entities.Identity;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure
{
public class CommunityContext : DbContext
{
public CommunityContext(DbContextOptions<CommunityContext> options) : base(options)
{
}
public DbSet<Article> Articles { get; set; }
public DbSet<Users> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
}
Unlike single context migration commands, multiple contexts command a little complicated. You have to specify the context name.
Create Migration(example of CommunityContext)
dotnet ef migrations add Initial -p Infrastructure/ -s API -o Data/Migrations -c CommunityContext
Update Migration(example of CommunityContext)
dotnet ef database update -p Infrastructure/ -s API -c CommunityContext
Create Migration(example of AppIdentityDbContext)
dotnet ef migrations add IdentityInitial -p Infrastructure -s API -o Identity/Migrations -c AppIdentityDbContext
Update Migration(example of AppIdentityDbContext)
dotnet ef database update -p Infrastructure -s API -c AppIdentityDbContext
Open the query editor.
Thank you 🧑🏻💻
Top comments (0)