我正在编写一个从sql数据库中读取数据的函数,其功能如下,
public override Dictionary<string, DbDataReader> GetData()
{
using (_connection)
{
Dictionary<string, DbDataReader> dataDictionary = new Dictionary<string, DbDataReader>();
_xmlDoc.Load("Queries.xml");
XPathNavigator navigator = _xmlDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("//query");
while (iterator.MoveNext())
{
_command = new SqlCommand(iterator.Current.ToString());
_command.Connection = _connection;
_command.CommandText = iterator.Current.ToString();
SqlDataReader reader = _command.ExecuteReader();
dataDictionary.Add(iterator.Current.GetAttribute("name", ""), reader);
}
return dataDictionary;
}
}
但我得到一个编译器错误,说明:
无法转换来源类型&#39; system.data.common.dbdatareader&#39;达到目标 键入&#39; system.data.sqlclient.sqldatareader&#39;
但我查看了MSDN:https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx
它表示ExecuteReader()的返回类型是&#39; system.data.sqlclient.sqldatareader&#39;
任何人都可以帮助我吗?谢谢!
答案 0 :(得分:1)
您的方法正在寻找Dictionary<string, DbDataReader>
的返回类型,但您将返回Dictionary<string, SqlDataReader>
。
public override Dictionary<string, DbDataReader> GetData()
{
using (_connection)
{
Dictionary<string, DbDataReader> dataDictionary = new Dictionary<string, DbDataReader>();
xmlDoc.Load("Queries.xml");
XPathNavigator navigator = _xmlDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("//query");
while (iterator.MoveNext())
{
DbCommand _command = db.GetSqlStringCommand(iterator.Current.ToString());
IDataReader dataReader = db.ExecuteReader(_command);
dataDictionary.Add(iterator.Current.GetAttribute("name", ""), dataReader);
}
return dataDictionary;
}
}
答案 1 :(得分:1)
更新代码将DbDataReader替换为IDataReader ..
public Dictionary<string, IDataReader> GetData()
{
using (_connection)
{
Dictionary<string, IDataReader> dataDictionary = new Dictionary<string, IDataReader>();
_xmlDoc.Load("Queries.xml");
XPathNavigator navigator = _xmlDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("//query");
while (iterator.MoveNext())
{
_command = new SqlCommand(iterator.Current.ToString());
_command.Connection = _connection;
_command.CommandText = iterator.Current.ToString();
IDataReader reader = _command.ExecuteReader();
dataDictionary.Add(iterator.Current.GetAttribute("name", ""), reader);
}
return dataDictionary;
}
}