I am having an issue saving a select query result to a model class.
I am trying to match values taken from an excel sheet with values from a local database. I keep getting the error "Data is Null. This method or property cannot be called on Null values " or something similar. I don't think I can be passing in null as I ran a SQL query to replace all nulls with 0. I also don't care if null is passed in to these properties, so either making the fields nullable or removing the nulls would work...I think?
The following is my code:
//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();
I can figure the match out, at this point I just want the "list.Add(new Client..." to work so that the while loop completes.