EF6 DBContext Dynamic Connection String

2019-01-14 02:57发布

问题:

public partial class ProcessContext : DbContext
{
    static ProcessContext()
    {
        Database.SetInitializer<ProcessContext>(null);
    }

    public ProcessContext()
        : base("Name=ProcessCS") //Comes from Config File
    {
    }

    --DBSets 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       --Code
    }
}

This is a Multi Tenent DB where we have 3 Different DB's. Centralized DB is in common location and would not be changed. This is where rest of the DB details will be stored. I need to create the Connection string @ runtime where the details will be coming from this centralized DB. Can some one please let me know how to go about it?

I tried with the following code, but it is not working. This Method will be called here

public ProcessContext()
    : base(nameOrConnectionString: ConnectionString())
{
}

private static string ConnectionString()
{
    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
    sqlBuilder.DataSource = "XXX";
    sqlBuilder.InitialCatalog = "YYY";
    sqlBuilder.PersistSecurityInfo = true;
    sqlBuilder.IntegratedSecurity = true;
    sqlBuilder.MultipleActiveResultSets = true;

    EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
    entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
    entityBuilder.Metadata = "res://*/";
    entityBuilder.Provider = "System.Data.SqlClient";

    return entityBuilder.ToString();
}

回答1:

For SQL Server connection, override the entity container class: (works in EF6, SQL server 2012 express, VS2013)

public partial class PxxxxEntities
{
    private PxxxxEntities(string connectionString)
        : base(connectionString)
    {
    }

    public static PxxxxEntities ConnectToSqlServer(string host, string catalog, string user, string pass, bool winAuth)
    {
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
        {
            DataSource = host,
            InitialCatalog = catalog,
            PersistSecurityInfo = true,
            IntegratedSecurity = winAuth,
            MultipleActiveResultSets = true,

            UserID = user,
            Password = pass,
        };

        // assumes a connectionString name in .config of MyDbEntities
        var entityConnectionStringBuilder = new EntityConnectionStringBuilder
        {
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = sqlBuilder.ConnectionString,
            Metadata = "res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl",
        };

        return new PxxxxEntities(entityConnectionStringBuilder.ConnectionString);
    }
}


回答2:

You should pass an ordinary connection string into the the DbContext constructor, not an entity connection string. So try changing your code as follows:

public ProcessContext()
    : base(ConnectionString())
{
}

private static string ConnectionString()
{
    SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
    sqlBuilder.DataSource = "XXX";
    sqlBuilder.InitialCatalog = "YYY";
    sqlBuilder.PersistSecurityInfo = true;
    sqlBuilder.IntegratedSecurity = true;
    sqlBuilder.MultipleActiveResultSets = true;

    return sqlBuilder.ToString();
}


回答3:

You have to change Web.config

<connectionStrings>
<add name="DefaultConnection" connectionString="data source=mydb;initial catalog=mydatabase;persist security info=True;user id=sa;password=password;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
<add name="DataContext" connectionString="data source=mydb;initial catalog=mydatabase;persist security info=True;user id=sa;password=password;multipleactiveresultsets=True;application name=EntityFramework" providerName="System.Data.SqlClient" />
<!-- Here Add multiple database connection string  -->


after you have to modify ProcessContext.cs file one constructor to create default connection

public ProcessContext()
      :base("name=DefaultConnection"){
        //here code
       }

other parametrise constructor dynamic connection to database

public ProcessContext(string DynamicConnectionString)
       :base(DynamicConnectionString){
// herer code }

here to default connection is "DefaultConnection" but you have chnage connection string given code any controller

ProcessContext db=new ProcessContext();//this is default connection

ProcessContext db=new ProcessContext("DataContext");//dynamic change connection string 

try this code



回答4:

This method worked well for me. I just added another named connection string to my app.config and then passed the name into the below GetDbContext() static method as shown below.

Example of usage:

var dbAlternate = PxxxxEntities.GetDbContext("PxxxxEntitiesAlternate")

Add the following to your project:

public partial class PxxxxEntities
{
    private PxxxxEntities(string name)
        : base("name=" + name)
    {
    }

    public static PxxxxEntities GetDbContext(string name)
    {
        return new PxxxxEntities(name);
    }
}


回答5:

Try to use an app.config file. Then call the desired connection string by its name:

using System.Configuration;

public ProcessContext()
    : base(ConnectionString("foo"))
{
}

private static string ConnectionString(string connKey)
{
    var conn = ConfigurationManager.ConnectionStrings[connKey].ConnectionString;
    return conn;
}