使用.net core mvc 将空值插入对象列表时出错?

error inserting nulls into List of objects using .net core mvc?

我在将 select 查询结果保存到模型 class 时遇到问题。

我正在尝试将取自 excel sheet 的值与本地数据库中的值相匹配。我一直收到错误 "Data is Null. This method or property cannot be called on Null values " 或类似的错误。我不认为我可以传递空值,因为我 运行 一个 SQL 查询用 0 替换所有空值。我也不关心是否将空值传递给这些属性,所以要么字段可为空或删除空值会起作用...我认为?

以下是我的代码:

 //initialize spreadsheet package,
        //load excel file, create dictionary of
        //naic/industry key/value pairs
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
        ExcelFile ef = ExcelFile.Load("C:/Data Sources/NAICS sheets/3-Digit-NAICS-Codes.xls");
        Dictionary<object, object> naics = new Dictionary<object, object>();

        //Connection string for local MSSQL database
        SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=gov_world;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");


        //Create array of client objects returned from query
        Client[] allRecords = null;
        string sql = "SELECT v_company, client_pk, v_naic_1, v_naic_2, v_naic_3, v_naic_4, v_naic_5 FROM  dbo._clients";

        //Iterate through elements of excel sheet, eventually inputting first column value
        //as key and second column value as value in dictionary
        foreach (ExcelWorksheet sheet in ef.Worksheets)
        {


            foreach (ExcelRow row in sheet.Rows)
            {
                object[] industry = new object[2];
                var count = 0;

                //populate industry array with all values of row
                foreach (ExcelCell cell in row.AllocatedCells)
                {
                    if (cell.Value != null)
                    {
                        industry[count] = cell.Value;
                    }
                    count++;
                }
                count = 0;

                //add values of first 2 cells to naics dictionary object
                naics.Add(industry[0], industry[1]);
                //Console.WriteLine(industry[0] + " | " + industry[1]);

                //reinitialize for every record
                industry[0] = 0;
                industry[1] = 0;

            }
        }


        //Set values from query to client model object, uses
        //to populate allRecords Array
        using (var command = new SqlCommand(sql, con))
        {
            con.Open();
            using (var reader = command.ExecuteReader())
            {
                var list = new List<Client>();
                while (reader.Read())
                    list.Add(new Client {
                        //Solution: write as v_company = reader[0] as string;
                        v_company = reader.GetString(0),
                        client_pk = reader.GetInt32(1),
                        v_naic_1 = reader.GetString(2),
                        v_naic_2 = reader.GetString(3),
                        v_naic_3 = reader.GetString(4),
                        v_naic_4 = reader.GetString(5),
                        v_naic_5 = reader.GetString(6)

                    });
                allRecords = list.ToArray();

            }
        }


        Console.WriteLine(allRecords[0].v_naic_1);
        Console.ReadLine();

我可以算出匹配结果,此时我只想让 "list.Add(new Client..." 工作以便 while 循环完成。

您需要检查所有值的 IsDBNull

if(!reader.IsDBNull(0))
{
  employee.FirstName = sqlreader.GetString(0);
}

或者您可以将其用作

reader[0] as string

另外最好使用列名而不是索引值,您可以通过列名获取列索引,如下所示:

int colIndex = reader.GetOrdinal(fieldname);

通过阅读 this 问题的所有答案,您可以找到有关如何从 reader 读取数据的更多信息和更好的方法。