Reputation: 6227
I've declared a nullable DateTime? NextUpdate
property 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; }
Upvotes: 0
Views: 115
Reputation: 206
Try following expression:
RootCause = (dataReader["RootCause"] is DBNull) ? (DateTime?)null : (DateTime?)dataReader["RootCause"] ;
Upvotes: 0
Reputation: 8725
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?
)
Upvotes: 1