如何从DataReader加载列数据
本文关键字:数据 加载 DataReader | 更新日期: 2023-09-27 18:22:42
我正在用EF7将应用程序移植到ASP.Net 5.0,发现了几个问题。其中一个问题是MS已删除DataTable。我试图转移一些代码,不使用DataTable,而是从SQLDataReader中读取,并将其记录到我拥有的实体中。我必须按列读取数据,但看起来datareader只能读取一次。
旧代码:
Series[] arrSeries = new Series[dt.Columns.Count - 1];
IList<Categories> arrCats = new List<Categories>();
Categories arrCat = new Categories();
foreach (DataColumn dc in dt.Columns)
{
var strarr = dt.Rows.Cast<DataRow>().Select(row => row[dc.Ordinal]).ToList();
if (dc.Ordinal == 0)
{
arrCat.category = strarr.Select(o => new Category { label = o.ToString() }).ToList();
}
else
{
Series s = new Series()
{
seriesname = dc.ColumnName,
renderas = null,
showvalues = false,
data = strarr.Select(o => new SeriesValue { value = o.ToString() }).ToList()
};
arrSeries[dc.Ordinal - 1] = s;
}
}
arrCats.Add(arrCat);
MultiFusionChart fusChart = new MultiFusionChart
{
chart = dictAtts,
categories = arrCats,
dataset = arrSeries
};
return fusChart;
新代码:
Series[] arrSeries = new Series[colColl.Count - 1];
IList<Categories> arrCats = new List<Categories>();
Categories arrCat = new Categories();
arrCat.category = new List<Category>();
for (int i = 0; i < reader.FieldCount; i++)
{
Series s = new Series()
{
seriesname = reader.GetName(i),
renderas = null,
showvalues = false
};
while (reader.Read())
{
if (i == 0)
{
Category cat = new Category();
cat.label = reader.GetValue(i).ToString();
arrCat.category.Add(cat);
}
else
{
SeriesValue sv = new SeriesValue();
sv.value = reader.GetValue(i).ToString();
s.data.Add(sv);
arrSeries[i - 1] = s;
}
}
}
arrCats.Add(arrCat);
MultiFusionChart fusChart = new MultiFusionChart
{
chart = dictAtts,
categories = arrCats,
dataset = arrSeries
};
return fusChart;
在代码工作的地方,它为Series返回null。我相信这是因为读者在录制《分类》时走到了最后。据我所知,不可能重置DataReader?
有没有办法将列数据从DataReader加载到List?或者,在这个例子中,我可以用其他方法替换DataTable?
您可以从多个columns
读取value
,方法是指定其index
,如下
int totalColumns = reader.FieldCount;
for(int i=0;i<totalColumns;i++)
{
var label = reader.GetValue(i);
}
您可以通过在列中循环来选择所有列的值。
GetValue
将int
作为argument
,这是列的index
而不是index of row
。
问题出在for循环中。首先,当你的i为0时,你已经初始化了一个"系列"对象S。之后,
while (reader.Read())
将阅读你的整个阅读器,而你的i仍然为零。所以只有
if(i == 0)
条件将返回true,您的整个读者将被消耗掉。之后,对于i>=1,
while (reader.Read())
将始终返回false,保留您的数组,arrSeries为空。删除while循环并使用索引直接从dataReader读取值
reader.GetValue(i);