简体   繁体   English

尝试从数据读取器读取值时发生转换错误

[英]Casting error while trying to read value from data reader

I am trying to read value from data reader based on column name but i am not getting in what data type(int,double,decimal) i should read that value because that column will have aggregate operations like sum,average,count,min,max etc... 我试图根据列名从数据读取器中读取值,但是我没有进入哪种数据类型(int,double,decimal),我应该读取该值,因为该列将具有诸如sum,average,count,min,max等...

I am getting below error when i am trying to data reader value in double datatype : 当我尝试使用double数据类型的数据读取器值时,出现以下错误:

double unitPrice = dr.GetDouble(0); // index of my column whose value i want to read from data reader

Error : Specified cast is not valid 错误:指定的转换无效

Sql Query : SQL查询:

select sum([UnitPrice]) AS unitPrice from [Sales].[SalesOrderDetail]

Further i have some calculations on this unitPrice variable so i am not getting what will be the best way to read this value and in what datatype? 此外,我对此unitPrice variable进行了一些计算,因此我无法获得读取该值和数据类型的最佳方法是什么?

Because of calculations on unitPrice variable i am not taking it as string otherwise i have to parse it everywhere in my calculations in double 由于对unitPrice variable进行了计算,因此我不将其视为字符串,否则我必须在计算中到处将其解析为double

I was having the same issue, using strong typing worked for me: 我遇到了同样的问题,使用强类型为我工作:

public Double unitPrice = Convert.ToDouble(dr["unitPrice"]);

or if you already know the index of the column you want to read: 或者如果您已经知道要读取的列的索引:

public Double unitPrice = Convert.ToDouble(dr(0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM