繁体   English   中英

object 无法从 dbnull 转换为其他类型

[英]object cannot be cast from dbnull change to other types

我的代码有一个错误,当我开始测试我的 web api 时,它显示 object 不能从 dbnull 转换为其他类型,我在 sql 服务器数据库中勾选了 null 框。 我不想更改数据库中的任何内容。 Mobile 和 datetime 列是 sql 服务器中的 null。 我用 asp.net web api 2 来做这个项目。

我的问题:如何在不对数据库做任何操作的情况下解决错误?

这是我的代码:

        public IHttpActionResult Get()
        {
            List<TestClass> draft = new List<TestClass>();
            string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
            SqlConnection sqlconn = new SqlConnection(mainconn);
            string sqlquery = "Select * From tblTest";
            sqlconn.Open();
            SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
            SqlDataReader sdr = sqlcomm.ExecuteReader();
            while (sdr.Read())
            {
                draft.Add(new TestClass()
                    {
                        UserId = Convert.ToInt32(sdr.GetValue(0)),
                        Name = sdr.GetValue(1).ToString(),
                        Mobile = sdr.GetValue(2).ToString(),
                        Access = Convert.ToInt32(sdr.GetValue(3)),
                        Date= Convert.ToDateTime(sdr.GetValue(4))
                    });
            }
            return Ok(draft);
        }

我的数据库在下面:

UserId Name     Mobile    Access  Date
11     John     NULL      2       2012-01-02 00:00:00.000
24     Fred     34786584  5       NULL
56     Emily    18375555  0       2014-03-04 00:00:00.000
76     Lydia    NULL      4       2015-09-08 00:00:00.000
87     Anna     12313147  5       2020-11-21 00:00:00.000
90     Mimi     27184641  1       NULL

您正在尝试将 null 值转换为 DateTime ,这会导致错误。 通过添加一个? 在 DateTime 属性之后签名。

通过 DateTime.TryParseExact 检查

DateTime.TryParseExact("YOURVALUE","yyyyMMdd",CultureInfo.InvariantCulture,DateTimeStyles.None, out resultvalue)?resultvalue.toString():"";

您可以使用IsDBNull进行检查:

 Date = sdr.IsDBNull(4) ? null : Convert.ToDateTime(sdr.GetValue(4))

如果 Date 列的类型为 'datetime' 或 'datetime2' 您可以使用GetDateTime

Date = sdr.IsDBNull(4) ? null : sdr.GetDateTime(4)

这段代码解决了

Date = (sdr.GetValue(4) != DBNull.Value) ? Convert.ToDateTime(sdr.GetValue(4)) : (DateTime?)null

暂无
暂无

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

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