0

Is there a better way to parse SqlDecimal from SqlDataReader to double than this?

class test {
    public double? Qte { get; set; }
}

SqlDataReader reader = cmd.executeReader();
reader.Read();

test t = new test() {
    Qte = (reader["DL_Qte"] == DBNull.Value) ? (double?)null : double.Parse(reader["DL_Qte"].ToString())
}
ebelair
  • 844
  • 11
  • 27
  • 1
    Whats `reader`? If it's a `SqlDataReader` you relaise it has a [`GetDouble` method](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getdouble(v=vs.110).aspx)? – Liam Jun 14 '17 at 14:58
  • reader is SqlDataReader – ebelair Jun 14 '17 at 14:59
  • Possible duplicate of [How to get float value with SqlDataReader?](https://stackoverflow.com/questions/37344167/how-to-get-float-value-with-sqldatareader) – Liam Jun 14 '17 at 15:00
  • If it's a decimal or money in database, why don't you store it as decimal in your model? – Tim Schmelter Jun 14 '17 at 15:04
  • I can't change my model from to – ebelair Jun 14 '17 at 15:12

2 Answers2

3

Here's the way I'd do it:

double d = reader.GetFieldValue<double>(reader.GetOrdinal("DL_Qte"));

GetFieldValue<T> is only available since .NET 4.5, so you can also do this:

double d = reader.GetDouble(reader.GetOrdinal("DL_Qte"));

EDIT:

To address the issue with nullable and DB null you're having, you could do something like this:

int columnIndex = reader.GetOrdinal("DL_Qte");

double? d = !reader.IsDBNull(columnIndex) ? 
    reader.GetFieldValue<double>(columnIndex) : new double?();
rory.ap
  • 34,009
  • 10
  • 83
  • 174
  • I get a System.InvalidCastException Qte is nullable (double?) – ebelair Jun 14 '17 at 15:07
  • Then use `double?` instead of `double`. – rory.ap Jun 14 '17 at 15:08
  • I get System.Data.SqlTypes.SqlNullValueException This method cannot be called on null values – ebelair Jun 14 '17 at 15:09
  • @ScottChamberlain -- I've run into trouble in the past with just null when using a ternary operator. I can't remember in what context or what happened, but it introduced a bug, and the solution was using this approach, which I've used ever since. – rory.ap Jun 14 '17 at 15:26
  • I think I know the quirk you are talking about and I think it only applies when the true condition of the operator is `null` and it can't infer the type, the false condition does not have the same problem. – Scott Chamberlain Jun 14 '17 at 15:28
1

If it's a decimal or money in database, why don't you store it as decimal in your model? You should also not parse a decimal to string and then to double, use the right method:

class Test {
    public decimal? Qte { get; set; }
}

...

int columnIndex = reader.GetOrdinal("DL_Qte");
decimal? qte = null;
if(!reader.IsDBNull(columnIndex))
    qte = reader.GetDecimal(columnIndex);  // <----- !!!
Test t = new Test { Qte = qte };
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939