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

时间:2011-04-14 19:22:34

标签: c# datetime

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

while (reader.Read())
{
    Status = reader["status"].ToString();
    Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1"));
}

我的get和set方法状态正常。但是,对于日期字段,我收到错误,因为有时来自数据库的字段是NULL值。如何修改我的方法来分配minvalue,因为数据库返回NULL?

public DateTime Event_Start_Date1
{
    get
    { return event_start_date1; }
    set
    { event_start_date1 = value; }
}

5 个答案:

答案 0 :(得分:2)

用一种方法包装逻辑:

private static DateTime GetDateTimeValue(SqlDataReader reader, string fieldName)
{
    int ordinal = reader.GetOrdinal(fieldName);
    return reader.IsDBNull(ordinal) ? reader.GetDateTime(ordinal) : DateTime.MinValue;
}

......并称之为:

Event_Start_Date1 = GetDateTimeValue(reader, "event_start_date1");

更通用和可重用的方法可以是将其转换为可以(可选)将默认值作为输入的扩展方法:

public static class SqlDataReaderExtensions
{
    public static DateTime GetDateTimeValue(this SqlDataReader reader, 
        string fieldName)
    {
        return GetDateTimeValue(reader, fieldName, DateTime.MinValue);
    }

    public static DateTime GetDateTimeValue(this SqlDataReader reader, 
        string fieldName, DateTime defaultValue)
    {
        int ordinal = reader.GetOrdinal(fieldName);
        return reader.IsDBNull(ordinal) 
            ? reader.GetDateTime(ordinal) 
            : defaultValue;
    }
}

这假定您无法更改模型。如果您有此选项,请改为使用Nullable<DateTime>,并使GetDateTimeValue方法默认返回null

答案 1 :(得分:2)

检查DBNull并根据您可以指定MinValue。

int ordinal = reader.GetOrdinal("event_start_date1");
Event_Start_Date1 = reader.IsDBNull(ordinal)? DateTime.MinValue: reader.GetDateTime(ordinal);

答案 2 :(得分:2)

使用可以为空的DateTime:

public DateTime? EventStartDate { get; set; }

类似于:

public Nullable<DateTime> EventStartDate { get; set; }

Read more about Nullable Types

要获取DateTime的默认值,您可以使用DateTime.MinValuedefault(DateTime)

while (reader.Read())
{
    Status = reader["status"].ToString();
    var startDate = reader.GetOrdinal("event_start_date1");
    EventStartDate = if reader.IsDBNull(startDate) ? 
                        reader.GetDateTime(ordinal) :
                        default(DateTime);
}

基本上,DateTimevalue-type,而不是引用类型,并且不能有空DateTime(或其他任何Value Type)编译时变量,为了能够保存空值,它必须包含在Nullable<T>中 在.NET中,所有非可空类型都有一个默认值,可以通过default关键字获取(例如default(DateTime))。

答案 3 :(得分:2)

使用DataReader.IsDBNull检查值是否为空:

Event_Start_Date1 = reader.IsDBNull("event_start_date1") ? DateTime.MinValue : 
reader.GetDateTime(reader.GetOrdinal("event_start_date1"));

上述句子的格式如下:

  

条件?接受的行动:拒绝   动作

答案 4 :(得分:1)

您可以使用try-catch

while (reader.Read())
{
    Status = reader["status"].ToString();
    try{
    Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1"));
    }
catch{
    Event_Start_Date1 = //some other thing
}

或者您可以使用GetSqlDateTime()

while (reader.Read())
{
    Status = reader["status"].ToString();
    Event_Start_Date1 = reader.GetSqlDateTime(reader.GetOrdinal("event_start_date1"));
}
相关问题