Multiple Provider in EntityFramework Core and Migrations
Hi, We will managing how to add multiple provider in ef core, like postgresql, sql server and sqllite
Starting Project
I'm creating as .net 7.0 web api in vs 2022
I'm creating folder called Entites to Domain and add two entity: User and Book
User and Book entities:
1 2 3 4 5 6 |
public class User { public int Id { get; set; } public string Name { get; set; } = string.Empty; public DateTime BirthDate { get; set; } } |
1 2 3 4 5 6 7 |
public class Book { public int Id { get; set; } public string Title { get; set; } = string.Empty; public string Author { get; set; } = string.Empty; public DateTime ReleaseDate { get; set; } } |
We are adding UserContext and BookContext in Data structure
1 2 3 4 5 6 7 8 9 10 11 12 |
public class UserContext : DbContext { public UserContext(DbContextOptions<UserContext> options) : base(options) { } public DbSet<User> Users { get; set; } = default!; protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserContext).Assembly); } } |
1 2 3 4 5 6 |
public class BookContext : DbContext { public BookContext(DbContextOptions<BookContext> contextOptions) : base(contextOptions) { } public DbSet<Book> Books { get; set; } = default!; } |
UserContext runs on SqlServer BookContext runs on Postgresql
Optional Configuration for User Entity
1 2 3 4 5 6 7 |
public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.Property(p => p.Name).HasMaxLength(100).IsRequired(); } } |
Setting Multiple Provider
We will using Npgsql provider for postgresql. We will register Contexts in Api structure. Before fill connection string to appSettings.json
1 2 3 4 |
"ConnectionStrings": { "UserContext": "Server=(localdb)\\mssqllocaldb;Database=UserDb;Trusted_Connection=True;MultipleActiveResultSets=true", "BookContext": "Server=127.0.0.1;Port=5432;Database=BookDb;User Id=postgres;Password=1234567;" } |
Program.cs:
1 2 3 4 5 6 7 8 |
builder.Services.AddDbContext<SqlServerContext>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("SqlServerContext"), x => x.MigrationsAssembly("EfMultipleProvider.Data")); }); builder.Services.AddDbContext<PostgreContext>(options => { options.UseNpgsql(builder.Configuration.GetConnectionString("PostgreContext")); }); |
Create Migration
We will create migrations with Powershell in Project Root Path. Done Before We look tags.
–project: Storage Migrations Project
–output-dir:
Migrations Folder Path
–context : The Context
–startup-project: Project in where Context is registered
UserContext migration:
1 |
dotnet ef migrations add UserInitial --context UserContext --output-dir ../Data/UserMigrations --startup-project Api --project Data |
BookContext migration
1 |
dotnet ef migrations add BookInitial --context BookContext --output-dir ../Data/BookMigrations --startup-project Api --project Data |
Created Migrations:
Apply Migrations:
There is two method. The first is update-database, Other is in runtime.
1.Update-Database
1 |
dotnet ef database update --context UserContext --project Data --startup-project Api |
2.Runtime
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static class RunMigrations { public static void ExecuteMigrations(this IServiceCollection services) { using var scope = services.BuildServiceProvider().CreateScope(); var userContext = scope.ServiceProvider.GetRequiredService<UserContext>(); if (userContext.Database.GetPendingMigrations().Any()) userContext.Database.Migrate(); var bookContext = scope.ServiceProvider.GetRequiredService<BookContext>(); if (bookContext.Database.GetPendingMigrations().Any()) bookContext.Database.Migrate(); } } |
1 |
builder.Services.ExecuteMigrations(); |
Example Insert:
1 2 3 4 5 6 |
app.MapGet("/user-insert", (UserContext context) => { context.Users.Add(new User { Name = "Banu" }); context.SaveChanges(); return Results.Ok(); }); |
Project's Github Url okankrdg/EfCoreMultipleProvider (github.com)
See you in the next article, with love