我有这个简化的类:
public abstract class BaseDaService
{
private readonly string _connectionString;
protected BaseDaService(string connectionString)
{
_connectionString = connectionString;
}
protected IDbConnection OpenConnection()
{
IDbConnection connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
}
这里的连接字符串来自配置文件。我想在执行操作时使用配置文件中的凭据:
new SqlConnection("context connection=true")
我可以在配置文件中调整连接字符串,还是可以操纵IDbConnection的“连接”实例来实现此目的?
最佳答案
我建议使用SqlConnectionStringBuilder类
// With a default parameter set to false you can still use
// the same code as before and change only the spots where
// the context is required
protected IDbConnection OpenConnection(bool useContext = false)
{
string newConString = _connectionString;
if(useContext)
{
SqlConnectionStringBuilder scs = new SqlConnectionStringBuilder(_connectionString);
scs.ContextConnection = true;
newConString = scs.ToString();
}
IDbConnection connection = new SqlConnection(newConString);
connection.Open();
return connection
}
当然,更改app.config只是一个偏好问题。