零框架多租户设计方案
This commit is contained in:
1 parent
b7caaa2d0c
commit
b4a704526d
42 files changed
+1002
-1
No files matched your search
+43
@@ -0,0 +1,43 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.DatabaseIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
namespace MultiTenancySample.DatabaseIsolationService.EntityFrameworks
|
||||
{
|
||||
public class DataSeeding(IDbContextFactory<DatabaseIsolationServiceDbContext> dbContext, ICurrentTenant currentTenant)
|
||||
{
|
||||
public async Task SeedDataAsync()
|
||||
{
|
||||
currentTenant.SetTenant("Tenant1");
|
||||
|
||||
DatabaseIsolationServiceDbContext dbContext1 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext1.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext1.AddRangeAsync(new List<Product> {
|
||||
new() { Id = Guid.NewGuid(), Name = "Product1"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product3"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product5"}
|
||||
});
|
||||
|
||||
await dbContext1.SaveChangesAsync();
|
||||
}
|
||||
|
||||
currentTenant.SetTenant("Tenant2");
|
||||
|
||||
DatabaseIsolationServiceDbContext dbContext2 = await dbContext.CreateDbContextAsync();
|
||||
|
||||
if (await dbContext2.Database.EnsureCreatedAsync())
|
||||
{
|
||||
await dbContext2.AddRangeAsync(new List<Product>
|
||||
{
|
||||
new() { Id = Guid.NewGuid(), Name = "Product2"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product4"},
|
||||
new() { Id = Guid.NewGuid(), Name = "Product6"}
|
||||
});
|
||||
|
||||
await dbContext2.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MultiTenancySample.DatabaseIsolationService.Entities;
|
||||
using MultiTenancySample.ServiceDefaults;
|
||||
|
||||
|
||||
namespace MultiTenancySample.DatabaseIsolationService.EntityFrameworks
|
||||
{
|
||||
public class DatabaseIsolationServiceDbContext(DbContextOptions<DatabaseIsolationServiceDbContext> options, ICurrentTenant currentTenant, IConfiguration configuration) : DbContext(options)
|
||||
{
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Product>().Property(p => p.Name).HasMaxLength(32);
|
||||
|
||||
base.OnModelCreating(modelBuilder);
|
||||
}
|
||||
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
if (currentTenant.TenantId != null)
|
||||
{
|
||||
string? connectionString = configuration.GetConnectionString(currentTenant.TenantId);
|
||||
|
||||
optionsBuilder.UseNpgsql(connectionString);
|
||||
}
|
||||
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user