gpt4 book ai didi

c# - Connectionstring 没有从 dbconnection 传递到 dbfactory?

转载 作者:搜寻专家 更新时间:2023-10-30 23:29:12 25 4
gpt4 key购买 nike

我目前正在使用 dbfactory?用于访问我的数据库,但由于某种原因,连接字符串在从 dbconnection` 初始化时为空?

怎么会?

代码:

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

关于c# - Connectionstring 没有从 dbconnection 传递到 dbfactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51585060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com