简体   繁体   English

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

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

I have a error with my code, when i start test with my web api and it shows object cannot be cast from dbnull change to other types and i have ticked the null box in sql server database.我的代码有一个错误,当我开始测试我的 web api 时,它显示 object 不能从 dbnull 转换为其他类型,我在 sql 服务器数据库中勾选了 null 框。 i don't want to change anything in database.我不想更改数据库中的任何内容。 The Mobile and datetime columns are null in sql server. Mobile 和 datetime 列是 sql 服务器中的 null。 I used asp.net web api 2 to do this project.我用 asp.net web api 2 来做这个项目。

My Questions: How to solve the error without doing anything in the database?我的问题:如何在不对数据库做任何操作的情况下解决错误?

here is my code:这是我的代码:

        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);
        }

My database in below:我的数据库在下面:

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

you are trying to convert a null value into DateTime which causes an error.您正在尝试将 null 值转换为 DateTime ,这会导致错误。 Make your date nullable by adding a?通过添加一个? sign after the DateTime property.在 DateTime 属性之后签名。

Check by DateTime.TryParseExact通过 DateTime.TryParseExact 检查

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

You can check using IsDBNull :您可以使用IsDBNull进行检查:

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

if Date column has type 'datetime' or 'datetime2' you can use GetDateTime :如果 Date 列的类型为 'datetime' 或 'datetime2' 您可以使用GetDateTime

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

This code solved it这段代码解决了

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