从会话

时间:2019-06-18 10:37:21

标签: c# asp.net-mvc entity-framework database-connection dbcontext

我正在尝试将连接字符串传递给Asp.Net MVC中的DBContext,并且当我向其传递静态变量时它可以工作。但是我的要求是从会话变量中传递连接字符串。

多个用户将拥有他们自己的数据库,因此我们存储  他们在会话中的连接字符串。

如何使用Session将连接字符串存储在HttpContext.Session中,并根据每个请求更改DBContext的连接字符串?

  

数据库上下文

 public MyContext(string nameOrConnectionString) : base(nameOrConnectionString)
    {

    }
  

会话变量

var session = httpContextAccessor.HttpContext.Session.GetString("ConnectionString");

1 个答案:

答案 0 :(得分:0)

我不知道这是否有帮助,但是我使用以下代码(略微整理)来动态生成我的连接字符串:

public partial class MastersContext : BaseContext
{
    public MastersContext(string connectionString)
        : base(connectionString, typeof(MastersContext), "Entities.Masters.MastersEF")
    {
    }

    public virtual DbSet<Groups> Groups { get; set; }
    public virtual DbSet<Materials> Materials { get; set; }
}

public class BaseContext : DbContext, IDbContext
{
    public BaseContext(string connectionString, Type contextType, string connectionMetadata)
                    : base(GetEntityConnectionString(connectionString,
                                                     contextType.GetTypeInfo().Assembly.GetName().Name,
                                                     connectionMetadata))
    {
        this.Initialise();
    }
}

public static string GetEntityConnectionString(string connectionString, string contextTypeName, string connectionMetadata)
{
    string result = string.Empty;

    EntityConnectionStringBuilder entityConnectionStringBuilder = new EntityConnectionStringBuilder //(System.Data.Entity.Core.EntityClient.EntityConnectionStringBuilder)
    {
        Provider = "System.Data.SqlClient",
        ProviderConnectionString = connectionString,
        Metadata = string.Format("res://{0}/{1}.csdl|res://{0}/{1}.ssdl|res://{0}/{1}.msl", contextTypeName, connectionMetadata)
    };

    result = entityConnectionStringBuilder.ToString();

    return result;
}