我当前正在使用dbfactory? for accessing my database, but for some reason is the connection string empty when it is being initialized from adbconnection`?
怎么会?
代码

        var connect = System.Configuration.ConfigurationManager.ConnectionStrings["Db"];
        DbConnection db = new SqlConnection(connect.ConnectionString);
        Console.WriteLine("DbConnection: " + db.ConnectionString);
        DbProviderFactory factory = DbProviderFactories.GetFactory(db);
        System.Data.Common.DbConnection cn = factory.CreateConnection();
        Console.WriteLine("DbConnection from factory: " + cn.ConnectionString);
        Repository = new Repository();
        return Repository.Load(() => cn);

输出:
DbConnection: Server=<connetionstring>
DbConnection from factory:

最佳答案

请尝试以下代码:

//get the information out of the configuration file.
var connectionStringSettings =
       ConfigurationManager.ConnectionStrings["Db"];

//get the proper factory and mandatory to have SQL Provide name in the connection string
DbProviderFactory factory =
  DbProviderFactories.GetFactory(connectionStringSettings.ProviderName);

//create a command of the proper type.
DbConnection conn = factory.CreateConnection();
//set the connection string
conn.ConnectionString = connectionStringSettings.ConnectionString;

//open the connection
conn.Open();

Repository = new Repository();
return Repository.Load(() => conn);

10-04 20:38