'Object cannot be cast from DBNull to other types.' 在存储过程中

'Object cannot be cast from DBNull to other types.' in stored procedure

我有一个方法试图从数据库中读取一些值 table DependencyList。它包含可以为空的列,例如 ReleaseIdTaskIdPhaseId。当其中一个为 NULL 时,我在阅读和尝试在视图中可视化它们时遇到问题。

代码如下所示:

public ActionResult FullIndex(int id)
{
        List<Dependency> dependencyList = new List<Dependency>();

        string connectionString = Configuration["ConnectionStrings:DefaultConnection"];

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string sql = "ReadFullDependencies";
            SqlCommand command = new SqlCommand(sql, connection);
            command.CommandType = CommandType.StoredProcedure;

            SqlParameter parameter = new SqlParameter
            {
                ParameterName = "@DependencyId",
                Value = id,
                SqlDbType = SqlDbType.VarChar,
                Size = 50
            };

            command.Parameters.Add(parameter);

            using (SqlDataReader dataReader = command.ExecuteReader())
            {
                while (dataReader.Read())
                {
                    Dependency dependency = new Dependency();
                    dependency.Id = Convert.ToInt32(dataReader["Id"]);
                    dependency.ReleaseId = Convert.ToInt32(dataReader["ReleaseId"]);
                    dependency.ReleaseName = ReadReleaseName(dependency.ReleaseId);
                    dependency.PhaseId = Convert.ToInt32(dataReader["PhaseId"]);
                    dependency.PhaseName = ReadPhaseName(dependency.PhaseId);
                    dependency.TaskId = Convert.ToInt32(dataReader["TaskId"]);
                    dependency.TaskName = ReadTaskName(dependency.TaskId);

                    dependencyList.Add(dependency);
                }
            }

            connection.Close();
        }

        return View(dependencyList);
}

如果它们在数据库中都是 not null,那么它就可以完美运行。但是,假设 ReleaseId 为 NULL。然后,在线:

dependency.ReleaseId = Convert.ToInt32(dataReader["ReleaseId"]);

我收到这个错误:

Object cannot be cast from DBNull to other types.

我试过在模型中的每个数据类型旁边加上问号 (?),但没有成功。

如何防止这种情况发生并将空值存储为 "None",例如,在模型中?

if (!dataReader.IsDBNull(dataReader.GetOrdinal("ReleaseId")))
     dependency.ReleaseId = Convert.ToInt32(dataReader["ReleaseId"]);

成功了。

您应该检查 DBNull 然后相应地分配值,就像这样

dependency.ReleaseId = dataReader["ReleaseId"] != System.DBNull.Value ? Convert.ToInt32(dataReader["ReleaseId"]) : 0;