在转换从SqlDataReader返回的可空日期时,指定的强制转换无效

时间:2016-06-24 10:19:38

标签: c# datetime casting sqldatareader

注意:这是how-to-get-nullable-datetime-out-of-the-database的副本,因为我特别想避免使用列索引

我有以下对象

public class MyClass 
{
    public int ID { get; set; }
    public DateTime? Deleted { get; set; }
}

和以下代码从数据库中提取所述对象

MyClass c = new MyClass();
using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = "MyConnectionString";
    SqlCommand cmd = new SqlCommand("SELECT ID,Deleted FROM MyTable", conn);
    conn.Open();
    SqlDataReader sdr = cmd.ExecuteReader();
    if (sdr != null && sdr.HasRows)
    {
        while (sdr.Read())
        {
            c.CampID = (int)sdr["ID"];
            c.Deleted = (DateTime?)sdr["Deleted"];
        }
        sdr.Close();
    }
    conn.Close();
}
return c;

如果删除日期为空,我会收到错误

  

指定的演员表无效

我做错了什么?如何以这种方式投射可以为空的日期时间字段?

我有两个丑陋的黑客可以完成工作。这样:

try{
    c.Deleted = (DateTime?)sdr["Deleted"];
}
catch{
    // ignoring a catch makes me feel unclean
}

或者

if(!string.isNullOrEmpty(sdr["Deleted"].ToString()))
{
    // not quite so bad, but still not very elegant
    c.Deleted = (DateTime?)sdr["Deleted"];
}

有更干净,更优雅的方式吗?

注意:我不希望使用字段索引,即

sdr.GetDateTime(i); 

2 个答案:

答案 0 :(得分:0)

希望这是有帮助的

c.Deleted = sdr["Deleted"] == DBNull.Value ? 
                  (DateTime?)null : Convert.ToDateTime(sdr["Deleted"]); 

答案 1 :(得分:-1)

测试一下:

c.Deleted = sdr["Deleted"] as DateTime?;