I'm trying to iterate my MySQL DB using MySqlDataReader in C# .Net but I'm having trouble checking whether any DateTime columns are null or empty first. I've made a dynamic list ("MyList") and plan to iterate the DB and add each item with custom fields, some of which are DateTimes, but during this process I'm getting the error "This method or property cannot be called on Null values."
With string values I usually use this inline syntax to check if the columns are null:
Value = reader["Name"] != null ? reader["Name"].ToString() : ""
but there seems to be a different process for DateTime columns which I can't figure out, here's a snippet of my code:
using MySql.Data.MySqlClient;
List<dynamic> MyList = new List<dynamic>();
using(MySqlConnection con = new MySqlConnection("server=localhost;database=database;user id=user;password=password")){
con.Open();
string sql = "SELECT * FROM Items";
DateTime defaultDate = DateTime.Now;
MySqlCommand cmd = new MySqlCommand(sql,con);
using(MySqlDataReader reader = cmd.ExecuteReader()){
while(reader.Read()){
MyList.Add(new {
Value = reader["Name"] != null ? reader["Name"].ToString() : "",
Date = reader.GetDateTime(reader.GetOrdinal("Date")) != null ? reader.GetDateTime(reader.GetOrdinal("Date")) : defaultDate
});
}
}
con.Close();
}