【发布时间】:2020-05-16 16:14:20
【问题描述】:
我正在开发一个基于多租户的应用程序,该应用程序将为每个学校/租户提供一个单独的数据库。每个模式将彼此相同。这个想法是使用 .NET Core 3 和 EF Core 拥有一个数据库上下文。
例如,客户端导航到 school1.gov.uk,然后使用存储在“school1”下的 appsettings.json 中的连接字符串来实例化 SchoolContext。
目前,我必须针对添加的每个新上下文运行 add-migration。任何人都可以想出一个解决方案,在单一上下文(即 SchoolContext )下运行一次迁移吗?
主要上下文
public class SchoolContext : DbContext
{ protected readonly IConfiguration _configuration;
private readonly IHttpContextAccessor _httpContextAccessor;
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public SchoolContext(IConfiguration configuration, IHttpContextAccessor httpContextAccessor)
{
_configuration = configuration;
_httpContextAccessor = httpContextAccessor;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var subdomain = _httpContextAccessor.HttpContext.Request.Host.Host;
var connectionString = _configuration.GetConnectionString(subdomain);
optionsBuilder.UseSqlServer(connectionString);
}
}
租户上下文 1
public class School1Context : SchoolContext
{
public Schoo1Context()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = _configuration.GetConnectionString("School1");
optionsBuilder.UseSqlServer(connectionString);
}
}
租户上下文 2
public class School2Context : SchoolContext
{
public School2Context()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var connectionString = _configuration.GetConnectionString("School2");
optionsBuilder.UseSqlServer(connectionString);
}
}
程序.cs
using (var scope = host.Services.CreateScope())
{
var school1Context = scope.ServiceProvider.GetService<School1Context>();
school1Context.Database.Migrate();
var school2Context = scope.ServiceProvider.GetService<School2Context>();
school2Context.Database.Migrate();
}
Appsettings.json
"ConnectionStrings": {
"School1": "Persist Security Info=true;Data Source=.\\SQLEXPRESS;Initial Catalog=School1;User ID=;Password=;",
"School2": "Persist Security Info=true;Data Source=.\\SQLEXPRESS;Initial Catalog=School2;User ID=;Password=;",
}
【问题讨论】:
标签: .net entity-framework asp.net-core .net-core entity-framework-4