Я пытаюсь создать таблицу схемы, специфичную для клиента, для многотенантного приложения. Что-то вроде ниже
CREATE SCHEMA Tenant1;
CREATE TABLE Tenant1.Customers (
CustomerId INT PRIMARY KEY,
Name NVARCHAR(100),
Email NVARCHAR(100),
Phone NVARCHAR(15)
);
CREATE SCHEMA Tenant2;
CREATE TABLE Tenant2.Customers (
CustomerId INT PRIMARY KEY,
Name NVARCHAR(100),
Email NVARCHAR(100),
Phone NVARCHAR(15)
);
DBContext
public class ApplicationDbContext : DbContext
{
private readonly string _schema;
public ApplicationDbContext(DbContextOptions options, string schema)
: base(options)
{
_schema = schema ?? "default_schema";
}
public ApplicationDbContext(DbContextOptions options)
: base(options)
{
_schema = "default_schema";
}
public virtual DbSet Customers { get; set; }
public virtual DbSet Tenants { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(_schema);
base.OnModelCreating(modelBuilder);
}
}
У меня есть два объекта
public class Customer
{
public Guid Id { get; set; }
public string Name { get; set; }
public string email { get; set; }
public string Phone { get; set; }
public DateTime CreatedOn { get; set; }
public bool IsActive => true;
}
public class Tenant
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Schema { get; set; }
}
program.cs
builder.Services.AddDbContext(optins =>
{
optins.UseNpgsql(builder.Configuration.GetConnectionString("postgresConnection"));
});
builder.Services.AddScoped();
// Seed initial data
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService();
await DataSeeder.SeedAsync(dbContext);
}
// Apply migrations for each tenant's schema
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService();
var dbContextFactory = scope.ServiceProvider.GetRequiredService();
var tenants = await dbContext.Tenants.ToListAsync();
foreach (var tenant in tenants)
{
var tenantContext = dbContextFactory.CreateDbContext(tenant.Schema);
await tenantContext.Database.MigrateAsync();
}
}
Однако таблицы создаются только в DEFAULT_SCHEMA. Схема, специфичная для клиента, не создается.
Фабричный метод
public sealed class TenantDbContextFactory
{
private readonly DbContextOptions _options;
public TenantDbContextFactory(DbContextOptions options)
{
_options = options;
}
public ApplicationDbContext CreateDbContext(string schema)
{
return new ApplicationDbContext(_options, schema);
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... cation-asp