【发布时间】:2015-10-20 17:06:33
【问题描述】:
我正在开发多租户应用程序 (ASP.NET 5 + EF7)。每个租户都有单独的数据库。我将为租户帐户数据创建一个单独的数据库。我已经在这个单独的数据库的启动类中注册了 EF 服务。我有迁移问题。在将tenantDbContext 注册为具有特定连接字符串的服务之前,我无法创建 EF 迁移。但是这个连接字符串对于每个租户来说必须是动态的......请问有什么想法吗?为租户管理 DbContexts 的最佳选择是什么?
未来的编辑 - protected override void OnConfiguring 是关键怎么做:请问这是一个好的解决方案吗?
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<TenantDbContext>();
public class TenantDbContext : IdentityDbContext<ApplicationUser>
{
public TenantDbContext() //development database with no connectionString in constructor
{
this._connectionString = "Connection String";
}
public TenantDbContext(string ConnectionString)
{
this._connectionString = ConnectionString;
}
private string _connectionString { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
...等
【问题讨论】:
-
我最初的想法是不要在启动时连接上下文,而是从工厂获取上下文。类似:
ContextFactory.Create(tenant)。对于迁移,您可以使用: Add-Migration MyMigration -ConnectionString "connection string here;" ? -
感谢您的回复。必须自动配置新租户 - C#... 想法:我可以在构造函数中使用特定的连接字符串实例化 DbContext 以进行连接。问题是如何在没有迁移的情况下创建数据库(在启动类中注册服务之前我无法创建迁移)我不会使用 SQL 脚本...
-
也许是第二个想法。是否可以通过数据库初始化程序创建没有迁移的数据库?如果是,未来如何管理数据库变更?
标签: asp.net asp.net-mvc entity-framework