[英]EF 6 - Switch between schema at runtime
I'm developing an ASP.NET 4.6.2 Web App with EF 6. The backend is a PostgreSQL database in several schemas : the tables and views are exactly the same in every schema. 我正在开发具有EF 6的ASP.NET 4.6.2 Web App。后端是采用几种模式的PostgreSQL数据库:每种模式中的表和视图都完全相同。 Depending on what the users do, I must connect specifically to one schema or another.
根据用户的操作,我必须专门连接到一个方案或另一个方案。
That works fine by overriding the OnModelCreating method but only once. 通过覆盖OnModelCreating方法(但仅覆盖一次),效果很好。
Should the user want to change his environment, I can instanciate the context with the right parameter but it doesn't call the OnModelCreating method. 如果用户想要更改其环境,则可以使用正确的参数实例化上下文,但是它不会调用OnModelCreating方法。 The context is kept somewhere and connects to the previous schema.
上下文保留在某处并连接到先前的架构。
-> How can I invalidate the context or force the switch to the other schema ? -> 如何使上下文无效或强制切换到其他模式?
Here's my code : 这是我的代码:
public partial class MyDB : DbContext
{
public Instances Instance { get; set; }
public string Schema
{
get
{
switch(Instance)
{
case Instances.I1:
return "schema1";
case Instances.I2:
return "schema2";
case Instances.I3:
return "schema3";
case Instances.I4:
return "schema4";
case Instances.I5:
return "schema5";
default:
return "public";
}
}
}
public MyDB(bool Proxy, Instances Instance)
: base("MyDB")
{
this.Configuration.ProxyCreationEnabled = Proxy;
this.Instance = Instance;
this.Database.Log = s => System.Diagnostics.Debug.Print(s);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema);
modelBuilder.Conventions.Add(new FunctionsConvention<MyDB>(Schema));
}
}
class NpgsqlConfiguration : DbConfiguration
{
public NpgsqlConfiguration()
{
SetModelCacheKey(ctx => new EntityModelCacheKey((ctx.GetType().FullName + ctx.Database.Connection.ConnectionString).GetHashCode()));
SetProviderServices("Npgsql", Npgsql.NpgsqlServices.Instance);
SetProviderFactory("Npgsql", Npgsql.NpgsqlFactory.Instance);
SetDefaultConnectionFactory(new Npgsql.NpgsqlConnectionFactory());
}
}
Thanks for your help ! 谢谢你的帮助 !
Its Simple use two connection strings 简单使用两个连接字符串
MyDB db;
if (user.Type == 1)
{
db = new MyDb("nameOfConnectionString1");
}
else
{
db = new MyDb("nameOfConnectionString2");
}
you may need to create overload for constructor 您可能需要为构造函数创建重载
public MyDB(string conStr, bool Proxy, Instances Instance)
: base(conStr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.