c# - 当 null 是数据库值时,如何在 get/set 方法中使用 datetime minvalue

标签 c# datetime

我有两个函数,在我的构造函数中,我从数据库中读取并调用我所有的集合函数:

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/

相关文章:

c# - 如何在没有 "runat=server"的情况下访问 C# 代码中的 HTML 控件?

c# - Enum.TryParse 对任何数值返回 true

mysql - 如何更改 mySQL NOW() 以便它适合另一个时区?

c# - 解析字符串时出现奇怪的错误?

c# - 类中的静态函数返回该类的实例

c# - 在桌面应用程序中管理 session 的 Ninject 范围

c# - 在 ASP.NET 网页中打开 PDF

mysql - Joomla 2.5 组件 - 存储日期/时间,显示在不同的时区

php - 如何在 PHP 中获取特定时间的下一个日期

python - 将 boto3 输出转换为方便的格式