指定的转换是无效
问题描述:
注:这是不是的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;
如果删除日期是NUL L I得到一个错误
指定的转换无效
我在做什么错?我怎样才能以这种方式抛出一个可空的日期时间字段?
我有两个丑陋的黑客可以完成工作。这:
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);
答
希望这是有益
c.Deleted = sdr["Deleted"] == DBNull.Value ?
(DateTime?)null : Convert.ToDateTime(sdr["Deleted"]);
答
测试此:
c.Deleted = sdr["Deleted"] as DateTime?;
+0
为什么默认为原始代码返回'null'的当前时间?为什么不只是'作为DateTime?'? –
+1
这甚至不应该编译。 – hvd
为'支票DBNull.Value'本身是正确和清晰的,但如果值已经存在,为什么要使用'Convert.ToDateTime'已知是一个'DateTime'?我并不是说这是错的,我说这个答案可以从解释中获益,而不仅仅是代码。 – hvd