背景
我正在制作一个c#4.0类进行重用,所以我可以向程序的大多数方法发送一个参数,并传递一个可以包含以下内容的'Connections'对象:
原因是我最终会升级到SQL Server,并且不想更改我的方法参数或代码。方法通常必须在同一个数据库中调用快速查询。
问题:
如何在下面的方法中为DbType(现在硬编码为整数1)正确设置(和调用)DRMDbConnection'set'参数的右侧:
set { drmDbConnection = SetDRMDbConnection(1); }
示例代码:
public class Connections
{
public string DRMDbConnectionString { get; set; }
private object drmDbConnection;
public object DRMDbConnection
{
get { return drmDbConnection; }
set { drmDbConnection = SetDRMDbConnection(1); }
}
private object SetDRMDbConnection(int DbType)
{
if (DbType == 1)
return new System.Data.OleDb.OleDbConnection();
else
return new SqlConnection();
}
}
10月31日编辑
我更新了类代码以使用推荐的IDbConnection,IDbCommand和IDataReader。注意:如果不更改SQL Server连接字符串,您将收到错误:“已经有一个与此命令关联的打开DataReader,必须先关闭它。”因此将此添加到连接字符串:“MultipleActiveResultSets = True;”
更新了类代码
public class Connections
// reusuable object to hold all database Connections and a convenient DataReader and Command object.
// Its purpose is to also be able to handle your choice of database connection, i.e. OleDb or SQL Server.
{
public string DRMConnectionString { get; set; }
public IDbConnection DRMConnection;
public IDbCommand DRMCommand
{
get { return DRMConnection.CreateCommand(); }
set { }
}
public int DRMConnectionType
// must be called to setup database connection and command. The connectionstring must be previously set.
{
set
{
if (value == 1)
DRMConnection = new System.Data.OleDb.OleDbConnection(DRMConnectionString);
else
DRMConnection = new SqlConnection(DRMConnectionString);
}
}
public void CloseConnections()
{
if (DRMCommand != null)
DRMCommand.Dispose();
if ((DRMConnection != null) && (DRMConnection.State != ConnectionState.Closed))
DRMConnection.Close();
}
}
调用代码
var conn = new Connections();
conn.DRMConnectionString = "my connection string";
conn.DRMConnectionType = 2;
conn.DRMConnection.Open();
try
{
using (var cmd = conn.DRMCommand)
{
cmd.CommandText = "SELECT * FROM MyTable";
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
CallSubMethodThatAlsoOpensDataReader(conn);
}
}
}
}
finally
{
conn.CloseConnections();
}
CallSubMethodThatAlsoOpensDataReader(Connections Conn)
{
using (var cmd = Conn.DRMCommand)
{
cmd.CommandText = "SELECT * FROM MyOtherTable";
using (var rdr = cmd.ExecuteReader()) // Error: There is already an open DataReader associated with this Command which must be closed first.
{
; // do stuff
}
}
}
答案 0 :(得分:1)
属性getter / setter不能带参数。您需要将其实现为方法。
答案 1 :(得分:1)
您可以按照以下方式运作:
public IDbConnection DRMDbConnection // Note the change of the type
{
get { return drmDbConnection; }
}
public int DrmDbConnectionType
{
set {
if (vale== 1)
drmDbConnection = new System.Data.OleDb.OleDbConnection();
else
drmDbConnection = new SqlConnection();
}
}
原因是我最终会升级到SQL Server,并且不想更改我的方法参数或代码。
我认为这是您要解决的关键问题。而不是编程到特定的类,编程到接口。具体来说,使用IDbConnection
代替SqlConnection
或OleDbConnection
可以让您隐藏确切类型,而不是将其封装在DRMDbConnection
中。