【发布时间】:2019-06-20 10:06:31
【问题描述】:
我有一个应用程序,其中数据保存在不同用户的不同 sql 模式中。
例如
用户 1 的数据保存在 SCHEMA1 中
用户 2 的数据保存在 SCHEMA2 中
以前的应用程序是在 MVC 3 中开发的,它运行良好且符合预期。
现在,我们正在迁移 .Net Core 2.2 中的应用程序,其中此功能不起作用
.net 核心没有IDbModelCacheKeyProvider,因为只有一个架构在工作
下面是 DBContext 文件
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
//public string Schema { get; set; }
private readonly IConfiguration configuration;
public string SchemaName { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext(string schemaname)
: base()
{
SchemaName = schemaname;
}
public DbSet<EmployeeDetail> EmployeeDetail { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:SchemaDBConnection"]);
var serviceProvider = new ServiceCollection().AddEntityFrameworkSqlServer()
.AddTransient<IModelCustomizer, SchemaContextCustomize>()
.BuildServiceProvider();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RemovePluralizingTableNameConvention();
modelBuilder.HasDefaultSchema(SchemaName);
base.OnModelCreating(modelBuilder);
}
public string CacheKey
{
get { return SchemaName; }
}
}
public class SchemaContextCustomize : ModelCustomizer
{
public SchemaContextCustomize(ModelCustomizerDependencies dependencies)
: base(dependencies)
{
}
public override void Customize(ModelBuilder modelBuilder, DbContext dbContext)
{
base.Customize(modelBuilder, dbContext);
string schemaName = (dbContext as ApplicationDbContext).SchemaName;
(dbContext as ApplicationDbContext).SchemaName = schemaName;
}
}
我的问题是如何在运行时更改 schemaName
那么组织该机制的正确方法是什么:
通过用户凭据找出架构名称; 从特定架构的数据库中获取用户特定的数据。
【问题讨论】:
-
IDbModelCacheKeyProvider不是关于模式的。您在 MVC 3 中使用的是一种解决方法,而不是在相同上下文中使用不同模式的正确方法 -
@PanagiotisKanavos 感谢您提供信息,我已经设法使用自定义 UserManager 和以下上下文类解决了这个问题。如果可能的话,您能否分享示例或 URL 以实现具有相同上下文的不同模式,这将很有帮助
标签: c# asp.net asp.net-mvc asp.net-core entity-framework-core