如何为现有连接建立动态创建的新数据库的连接字符串?

时间:2017-12-30 06:52:52

标签: c# database entity-framework connection-string

我有查询动态创建数据库。

    private void ExecuteNonQuery(string sql)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            connection.Open();
            SqlCommand command = connection.CreateCommand();
            command.CommandText = sql;
            command.ExecuteNonQuery();
        }
    }

    private void CreateDatabase(string databaseName)
    {
        try
        {
            ExecuteNonQuery($"CREATE DATABASE {databaseName}");
        }
        catch (Exception e)
        {
            throw new Exception($"Can't create database '{databaseName}'");
        }
    }

将使用我现有的连接创建数据库,但我需要为此新数据库创建连接字符串以运行迁移以及用于各种其他目的。

怎么可能?

更新

它的实际用途是用户可以填写表单以创建新数据库,以便他们可以提供现有的连接字符串,或者如果他们没有手头有我们为他们构建它

3 个答案:

答案 0 :(得分:0)

使用此函数获取与新数据库的连接:

private SqlConnection NewDatebaseConnection(string databaseName)
    {
        SqlConnection  connection = new SqlConnection(_connectionString);
        connection.ChangeDatabase(databaseName);
        return SqlConnection;  
    }

答案 1 :(得分:0)

如果您使用EF,您应该有一个上下文可以使用,如下所示:

public class MyContext : DbContext
{
    public MyContext():base("myConnectionStringName")
    {
    }
}

constructor有一个参数,用于指定连接名称或连接字符串。因此,您可以获取所需的任何连接字符串的上下文:

using (var db = new MyContext("connection_string_containing_new_db") 
{
    // do stuff with the context
}

您应该考虑使用构建此类上下文的工厂:

class MyContextFactory
{
    MyContext CreateContextForDatabase(string dbName) 
    {
         var builder = new SqlConnectionStringBuilder();
         builder["Data Source"] = "server\\instance";
         builder["integrated Security"] = true;
         builder["Initial Catalog"] = dbName;

         return new new MyContext(builder.ConnectionString);
    }
}

代码使用SqlConnectionStringBuilder构建(从头开始)连接字符串。另一种方法是使用var builder = new SqlConnectionStringBuilder(staticConnectionString)解析静态连接字符串,仅更改Initial Catalog

答案 2 :(得分:0)

要保存新连接,您可以将ConnectionStringBuilder与现有连接一起使用,更改数据库名称并将其保存到app.config

1.获取连接字符串的方法:

string GetConnectionString(string name) =>
          ConfigurationManager.ConnectionStrings[name].ConnectionString;

2.Helper方法,将新连接字符串保存到app.config:

void CreateNewConnectionString(string baseName, string newName, string newDatabaseName)
{
    // Get the connection string a new connection will be based on
    string baseConnString =
        ConfigurationManager.ConnectionStrings[baseName].ConnectionString;
    // For simplicity of manipulations with connection strings,
    // we use SqlConnectionStringBuilder, passing it an existing connection string
    var connBuilder = new SqlConnectionStringBuilder(baseConnString);
    // Change existing database name to the new database name
    connBuilder.InitialCatalog = newDatabaseName;
    // Create new settings, holding our new connection string
    var newConnection = new ConnectionStringSettings(newName, connBuilder.ToString());
    // Save new connection string
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.ConnectionStrings.ConnectionStrings.Add(newConnection);
    config.Save(ConfigurationSaveMode.Modified);
}

3.Usage

private void CreateDatabase(string databaseName)
{
    try
    {
        // Create database using "main" connection string
        ExecuteNonQuery($"CREATE DATABASE {databaseName}", "main");
        // Create new connection string "my_db" based on "main"
        CreateNewConnectionString("main", "my_db", databaseName);
    }
    catch (Exception e)
    {
        throw new Exception($"Can't create database '{databaseName}'");
    }
}