我正在尝试创建OracleConnectionStringBuilder
或SqlConnectionStringBuilder
的新对象,具体取决于发送给函数的数据库提供程序。
无法弄清楚如何以最短(和可读)的方式做到这一点。
我从:
开始var isIntegratedSecuritySet = string.IsNullOrEmpty(UserId) || string.IsNullOrEmpty(Password);
var connBuilder = new SqlConnectionStringBuilder()
{
DataSource = DataSource,
UserID = UserId,
Password = Password,
InitialCatalog = InitialCatalog,
ConnectTimeout = 15,
IntegratedSecurity = isIntegratedSecuritySet
};
return connBuilder.ConnectionString;
}
但是现在Oracle没有IntegratedSecurity
,它有PersistSecurityInfo
。
所以我试试这个:
var isIntegratedSecuritySet = string.IsNullOrEmpty(UserId) || string.IsNullOrEmpty(Password);
var connBuilder = new DbConnectionStringBuilder();
try
{
if (Providor.Equals(DatabaseProvidors.Oracle))
{
connBuilder = new OracleConnectionStringBuilder()
{
PersistSecurityInfo = isIntegratedSecuritySet
};
}
else if (Providor.Equals(DatabaseProvidors.SqlServer))
{
connBuilder = new SqlConnectionStringBuilder()
{
IntegratedSecurity = isIntegratedSecuritySet
};
}
但现在我需要将属性转换为一个或另一个
((SqlConnectionStringBuilder)connBuilder).DataSource = DataSource;
等。
如果能够以完整的形式明确定义这两者,我能做什么才能做到这一点:
var isIntegratedSecuritySet = string.IsNullOrEmpty(UserId) || string.IsNullOrEmpty(Password);
try
{
if (Providor.Equals(DatabaseProvidors.Oracle))
{
var connBuilder = new OracleConnectionStringBuilder()
{
DataSource = DataSource,
UserID = UserId,
Password = Password,
ConnectionTimeout = 15,
PersistSecurityInfo = isIntegratedSecuritySet
};
//if (InitialCatalog != null)
// connBuilder.InitialCatalog = InitialCatalog;
return connBuilder.ConnectionString;
}
else if (Providor.Equals(DatabaseProvidors.SqlServer))
{
var connBuilder = new SqlConnectionStringBuilder()
{
DataSource = DataSource,
UserID = UserId,
Password = Password,
ConnectTimeout = 15,
IntegratedSecurity = isIntegratedSecuritySet
};
if (InitialCatalog != null)
connBuilder.InitialCatalog = InitialCatalog;
return connBuilder.ConnectionString;
}
}
答案 0 :(得分:1)
为什么不使用通用DbConnectionStringBuilder
?
var connBuilder = new System.Data.Common.DbConnectionStringBuilder();
connBuilder.Add("Data Source", DataSource);
connBuilder.Add("User Id", UserId);
connBuilder.Add("Password", Password);
if (Providor.Equals(DatabaseProvidors.Oracle)) {
connBuilder.Add("Persist Security Info", isIntegratedSecuritySet);
connBuilder.Add("Connection Timeout", ConnectionTimeout);
} else if (Providor.Equals(DatabaseProvidors.SqlServer)) {
connBuilder.Add("Integrated Securiry", isIntegratedSecuritySet);
connBuilder.Add("Connect Timeout", ConnectionTimeout); // Not sure about this property
}