A
A
Arseniy2014-05-18 10:35:52
C++ / C#
Arseniy, 2014-05-18 10:35:52

How to add an element to a collection from the database if the field in the database can be null

class _Explain
{
        public int ID { get; set; }
        public string SelectType { get; set; }
        public string Table { get; set; }
        public string Type { get; set; }
        public string PossibleKeys { get; set; }
        public string Key { get; set; }
        public int KeyLen {get; set;}
        public string Ref { get; set; }
        public int Rows { get; set; }
        public string Extra { get; set; }
}
...
using (MySqlDataReader rdr = cmd.ExecuteReader())
{
                while (rdr.Read())
                {
                    expList.Add(new _Explain
                    {
                        ID = Convert.ToInt32(rdr["id"]),
                        SelectType = rdr["select_type"].ToString(),
                        Table = rdr["table"].ToString(),
                        Type = rdr["type"].ToString(),
                        PossibleKeys = rdr["possible_keys"].ToString(),
                        Key = rdr["key"].ToString(),
                        KeyLen = Convert.ToInt32(rdr["key_len"]),
                        Ref = rdr["ref"].ToString(),
                        Rows = Convert.ToInt32(rdr["rows"]),
                        Extra = rdr["Extra"].ToString()
});

Error: Cannot cast this object from DBNull to another type.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Kulakov, 2014-05-19
@Trytge

First of all, please try to be more specific next time.
secondly, you can try something like this
SomeValue = (<field that can be null in the database> is DBNull) ? null : <script when not DBNull>
here we check in parentheses that the type of the object is DBNull, after the question comes an expression if the condition is true, after the colon comes an expression if the condition is false.
For example,
and, accordingly, use a type that can be null

A
Alexander, 2014-05-18
@avorsa

public string ?Type { get; set; }
Look at nullable types

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question