Error Message: Unable to cast object of type 'System.DBNull' to type 'System.String'.

Rashmi
Rashmi
1214 Points
21 Posts

I'm trying to execute a store procedure in .net 9.0 with SQL command. For nullable field getting following error:

Error Message: Unable to cast object of type 'System.DBNull' to type 'System.String'. 
Error: {"ClassName":"System.InvalidCastException","Message":"Unable to cast object of type 'System.DBNull' to type 'System.String'.","Data":null,"InnerException":null,"HelpURL":null,"StackTraceString":" at

Here is code:

using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
    sqlConnection.Open();
    var command = new SqlCommand("GetChildren", sqlConnection);
    command.CommandType = CommandType.StoredProcedure;
    command.Connection = sqlConnection;
    command.CommandTimeout = 100;

    var param1 = command.Parameters.Add("@ParentId", SqlDbType.Int);
    param1.Value = parentComponent.Id;
    var param2 = command.Parameters.Add("@ParentType", SqlDbType.VarChar);
    param2.Value = parentComponent.Type;

    var reader = command.ExecuteReader();
    while (reader.Read())
    {
        var child = new Component
        {
            ComponentId = (int)reader["Id"],
            Name = (string)reader["Name"]
            ImageURL = (string)reader["ImageURL"]
        };
        children.Add(child);
    }
Views: 58
Total Answered: 1
Total Marked As Answer: 1
Posted On: 13-Aug-2025 05:00

Share:   fb twitter linkedin
Answers
chatGPT
chatGPT
202 Points
0 Posts
         

Here the problem is in these casts:

Name = (string)reader["Name"]
ImageURL = (string)reader["ImageURL"]

If Name or ImageURL is NULL in the database, reader["..."] returns DBNull.Value, and (string) will

Replace with null checks or Convert.ToString():

Name = reader["Name"] == DBNull.Value ? null : (string)reader["Name"],
ImageURL = reader["ImageURL"] == DBNull.Value ? null : (string)reader["ImageURL"]

OR

Name = Convert.ToString(reader["Name"]),
ImageURL = Convert.ToString(reader["ImageURL"])

 

Extra tip

 

If you expect empty strings instead of nulls, you can do:

Name = Convert.ToString(reader["Name"]) ?? "",
ImageURL = Convert.ToString(reader["ImageURL"]) ?? ""

That way you won’t have to check for null later when using Name or ImageURL.

 

Posted On: 13-Aug-2025 05:07
thanks
 - Rashmi  13-Aug-2025 23:34
 Log In to Chat