0

I've declared a nullable DateTime? NextUpdateproperty in my model and database.

I can update the DateTime value fine on my DB as it allows null for this field.

But when I try to get the value of NextUpdate field from the database using SQL Data Reader it bombs out because the value of NextUpdate is null.

I did try to init the NextUpdate value if it is null using the following assignment but the error is still thrown telling me that field is null:

NextUpdate = dataReader.GetDateTime(dataReader.GetOrdinal("NextUpdate")) != null ? dataReader.GetDateTime(dataReader.GetOrdinal("NextUpdate")) : DateTime.MinValue,

Error:

Data is Null. This method or property cannot be called on Null values -  at System.Data.SqlClient.SqlBuffer.get_DateTime()

Question:

Is there a short method of reading back and initializing a nullable **DateTime?** value?

Code:

using (IDataReader dataReader = db.ExecuteReader(dbCommand))
{
   if (dataReader.Read())
   {
      esc = new Escalation
      {
          NextUpdate = dataReader.GetDateTime(dataReader.GetOrdinal("NextUpdate")),
          RootCause = dataReader["RootCause"] != null ? dataReader["EM"].ToString() : ""
      };
   }
}

Property in Model:

    public DateTime? NextUpdate { get; set; }
1
  • Are you sure that your IDataReader always have a column named NextUpdate ? Commented Jun 2, 2016 at 11:24

2 Answers 2

1

Compare the value against DBNull.Value instead of null:

NextUpdate = dataReader["NextUpdate"].Equals(DBNull.Value) ? (DateTime?)null : (DateTime?)dataReader["NextUpdate"]

(assuming that the NextUpdate member is a DateTime?)

Sign up to request clarification or add additional context in comments.

Comments

0

Try following expression:

RootCause = (dataReader["RootCause"] is DBNull) ? (DateTime?)null :  (DateTime?)dataReader["RootCause"] ;

2 Comments

NextUpdate is the DateTime? field not RootCause.
@Brian J exactly.

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.