Reputation: 1265
I want to read a number of type decimal(8,2)
from a SQL Server database, and store them in an object, MyRow
.
public class MyRow
{
public decimal data1 { get; set; }
}
...
List<MyRow> values = new List<MyRow>();
SqlDataReader reader = command.ExecuteReader();
while (reader.read())
{
values.Add( new MyRow() {
data1 = decimal.Parse(((double)reader["data1"]).ToString("R"))
}
}
This solution seems far from ideal, and it seems like I'm doing too much conversion for something that seems like it would be fairly simple. Since the values for data
are already decimal(8,2)
in the database, is there any way to read the data into a decimal
type without the conversion from an object
to a decimal
?
Upvotes: 2
Views: 6924
Reputation: 1
Use Precision and Scale
Here the code snippet
// Assume, com is SqlCommand and ExchangeRate is Parameter
SqlParameter parameter = new SqlParameter("@ExChangedRate", SqlDbType.Decimal);
parameter.Direction = ParameterDirection.Output;
parameter.Precision = 16;
parameter.Scale = 2;
com.Parameters.Add(parameter);
Upvotes: 0
Reputation: 53958
You could use the GetDecimal
method of SqlDataReader
. A SqlDataReader
object implmements the IDataRecord
interface. Hence, it implements many methods. Among these methods, there is the GetDecimal
.
For further information on this, please have a look here.
That being said, your code can be written as below:
List<MyRow> values = new List<MyRow>();
SqlDataReader reader = command.ExecuteReader();
while (reader.read())
{
values.Add(new MyRow()
{
data1 = reader.GetDecimal(reader.GetOrdinal("data1"))
});
}
Upvotes: 2
Reputation: 218782
Use SqlDataReader's GetDecimal method.
var values = new List<MyRow>();
while (reader.Read())
{
var r = new MyRow { data1 = reader.GetDecimal(reader.GetOrdinal("data1"))};
values.Add(r);
}
Upvotes: 0