繁体   English   中英

从数据库获取数据作为日期时间时出现 InvalidCastException

[英]InvalidCastException when getting data from Database as a datetime

我正在尝试从我的数据库中提取一些数据,但是当涉及到Datetime时,我得到了一个

无效转换异常

这是我的数据库(SQL SERVER)

Create table Timeline(
start date,
end date
)

表时间轴

start(date)            end(date)
03/07/2020             NULL
NULL                   10/07/2020
15/07/2020             25/07/2020

这是我的查询

SELECT Timeline.start, Timeline.end FROM Timeline

这是我的 c# 代码

public class Timeline
{
    public DateTime? startDate;
    public DateTime? endDate;


    public static Timeline fromRow(DataRow r)
    {
        Timeline a = new Timeline();
        
        a.startDate = r.Field<DateTime?>("start");
        a.endDate = r.Field<DateTime?>("end");

        return a;
    }
}

当我拉出NULL值时,它可以工作,但是当我拉出像03/07/2020这样的真实日期时,它给了我InvalidCastException 有没有办法在将值放入变量之前检查值?

这是因为列类型与您尝试在此处转换的内容不匹配,我猜它被引用为 varchar 类型构造函数 public DataColumn (string columnName) ,这很好,我们可以安全地将日期解析为一个字符串,你可能会失去几个周期,但这不再是 1995 年了。 如果您想安全地转换而不是为列提供正确的类型,那么构造函数 public DataColumn (string columnName, Type type)


// Change Names to match C# nameing conventions
public class TimeLine
{
    // Since this class is just a strongly typed object for rows of your table values should not be able to change.
    public DateTime? StartDate { get; private set; }
    public DateTime? EndDate { get; private set; }


    public static TimeLine FromRow(DataRow r)
    {
        // Casting will depend if we know the DataColumns type, if we dont we can just parse the string value
        return new TimeLine
        {
            StartDate = DateTime.TryParse(r.Field<string>("start"), out var sd) ? sd : (DateTime?)null,
            EndDate = DateTime.TryParse(r.Field<string>("end"), out var ed) ? ed : (DateTime?)null,
        };
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM