简体   繁体   中英

Object cannot be cast from DBNull to other types Linq

I am facing error Object cannot be cast from DBNull to other types.

I tried to ingore null values, even though am getting same DBNull error. How to handle this error?

List<string> List = new List<string>();
 List = (from r in Dt.AsEnumerable()
                                 orderby Convert.ToDateTime(r["StartDate"]) descending
                                                select r["name"] + string.Empty).ToList();

Since you're dealing with LINQ-to-Objects, you can use your own custom conversion, perhaps something like:

static DateTime? CustomParseDateTime(object value) {
    if(value == null || value is DBNull) return null;
    return Convert.ToDateTime(value);
}

and

orderby CustomParseDateTime(r["StartDate"])

No problem. The following code will fix your problem, requires no additional methods, and unlike Mark Gravell's solution, handles r["name"].

var list = new List<string>();
list = (from r in Dt.AsEnumerable()
    orderby Convert.ToDateTime(r["StartDate"] == DBNull.Value ? "1/1/1" : r["StartDate"].ToString()) descending
    select (r["name"] == DBNull.Value ? string.Empty : r["name"].ToString())).ToList();

1/1/0001 is the default value for DateTime. So if r["StartDate"] == DBNull.Value, the expression evaluates to the same value as "new DateTime()".

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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