EF6 DBContext动态连接字符串

时间:2014-01-16 15:03:42

标签: entity-framework asp.net-mvc-4 .net-4.5 dbcontext

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
    }
}

这是一个Multi Tenent DB,我们有3个不同的DB。集中式数据库位于公共位置,不会更改。这是存储其余数据库详细信息的位置。我需要创建连接字符串@ runtime,其中详细信息将来自此集中式数据库。有人可以让我知道如何去做吗?

我尝试使用以下代码,但它无效。这个方法将在这里调用

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();
}

6 个答案:

答案 0 :(得分:24)

对于SQL Server连接,覆盖实体容器类:(适用于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);
    }
}

答案 1 :(得分:14)

您应该将普通连接字符串传递给DbContext构造函数,而不是实体连接字符串。因此,请尝试按如下方式更改代码:

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();
}

答案 2 :(得分:3)

您必须更改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  -->


在必须修改ProcessContext.cs文件之后 一个构造函数来创建默认连接

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

其他参数化构造函数动态连接到数据库

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

此处默认连接是&#34; DefaultConnection&#34;但你有chnage连接字符串给定代码任何控制器

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

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

试试这段代码

答案 3 :(得分:1)

这种方法对我很有用。我刚刚在app.config中添加了另一个命名连接字符串,然后将名称传递给下面的GetDbContext()静态方法,如下所示。

使用示例:

var dbAlternate = PxxxxEntities.GetDbContext("PxxxxEntitiesAlternate")

将以下内容添加到您的项目中:

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

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

答案 4 :(得分:1)

尝试使用app.config文件。然后按名称调用所需的连接字符串:

using System.Configuration;

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

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

答案 5 :(得分:0)

动态连接字符串EF

使用此代码:

    public Entities(): base(ConnectToSqlServer())
    {
    }



    public static string ConnectToSqlServer()
    {
        SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder
        {
            DataSource = "ServerName",
            InitialCatalog = "DatabaseName",
            PersistSecurityInfo = true,
            IntegratedSecurity = false,
            MultipleActiveResultSets = true,

            UserID = "Username",
            Password = "Password",
        };
        var entityConnectionStringBuilder = new EntityConnectionStringBuilder
        {
            Provider = "System.Data.SqlClient",
            ProviderConnectionString = sqlBuilder.ConnectionString,
            Metadata = "res://*/Data.Database.csdl|res://*/Data.Database.ssdl|res://*/Data.Database.msl",
        };

        return entityConnectionStringBuilder.ConnectionString;
    }