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())
}
5
  • 1
    Whats reader? If it's a SqlDataReader you relaise it has a GetDouble method? Commented Jun 14, 2017 at 14:58
  • reader is SqlDataReader Commented Jun 14, 2017 at 14:59
  • Possible duplicate of How to get float value with SqlDataReader? Commented Jun 14, 2017 at 15:00
  • If it's a decimal or money in database, why don't you store it as decimal in your model? Commented Jun 14, 2017 at 15:04
  • I can't change my model from <double?> to <decimal?> Commented Jun 14, 2017 at 15:12

2 Answers 2

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?();
Sign up to request clarification or add additional context in comments.

5 Comments

I get a System.InvalidCastException Qte is nullable (double?)
Then use double? instead of double.
I get System.Data.SqlTypes.SqlNullValueException This method cannot be called on null values
@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.
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.
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 };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.