coalescing operator work in this case?

This question already has an answer here:

  • Unable to cast object of type 'System.DBNull' to type 'System.String` 10 answers
  • What do two question marks together mean in C#? 16 answers

  • DBNull isn't the same as null , so you can't use the ?? operator. You have to handle this case separately.

    Replace:

    Make = (string)(rdr["Make"] ?? ""),
    

    with:

    Make =  (rdr["Make"] == System.DBNull.Value ? "" : (string)rdr["Make"]),
    

    SqlDataReader returns a DBNull object, which is not a C# null - it is an object representing a NULL value in the database.

    You have a number of options, and creating a method to handle that might be most readable and save you on repeating code:

    private static string GetStringOrEmpty(object dbValue){
        return dbValue == System.DBNull.Value ? string.Empty : (string)dbValue;
    }
    

    and then

    Make = GetStringOrEmpty(rdr["Make"]),
    

    Alternatively look into Dapper which is a very small but powerful ORM that will handle a lot of this stuff for you.

    链接地址: http://www.djcxy.com/p/53848.html

    上一篇: 这个关键字和双重问号(??)混淆了我

    下一篇: 在这种情况下合并操作员工作?