我有两个函数,在我的构造函数中,我从数据库中读取并调用我所有的集合函数:
while (reader.Read())
{
Status = reader["status"].ToString();
Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1"));
}
我的状态获取和设置方法工作正常。但是,对于日期字段,我收到一个错误,因为有时来自数据库的字段是 NULL 值。如果数据库返回NULL,我将如何修改我的方法来分配最小值?
public DateTime Event_Start_Date1
{
get
{ return event_start_date1; }
set
{ event_start_date1 = value; }
}
最佳答案
使用DataReader.IsDBNull检查该值是否为空:
Event_Start_Date1 = reader.IsDBNull("event_start_date1") ? DateTime.MinValue :
reader.GetDateTime(reader.GetOrdinal("event_start_date1"));
上面的语句格式如下:
Condition ? accepted action : rejected action
关于c# - 当 null 是数据库值时,如何在 get/set 方法中使用 datetime minvalue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5668531/