0

I am trying to pass connection string to my DBContext in Asp.Net MVC and it worked when I pass a static variable to it. But my requirement is to pass the connection string from session variable.

Multiple user will have their their own database, therefore we store their connection string in Session.

How can I use Session to store connection string in HttpContext.Session and change connection string of DBContext by Per Request?

DB Context

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

    }

Session variable

var session = httpContextAccessor.HttpContext.Session.GetString("ConnectionString");
Surya
  • 168
  • 4
  • 19

1 Answers1

0

I don't know if this helps but I dynamically generate my connection string using the following code (trimmed down a little):

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;
}
Mark Ball
  • 366
  • 2
  • 10