My code:
ret.chromeVehicles = _context.Database.SqlQuery<ChromeVehicle>("SELECT Year, Make, Model, ModelNumber, MIN(VIN) as VIN FROM DealerInventory WHERE DealerID = 1 GROUP BY Year, Make, Model, ModelNumber").ToList();
List<Thread> threadList = new List<Thread>();
foreach (ChromeVehicle vehicle in ret.chromeVehicles)
{
var thread = new Thread(delegate () {
// Here is an API call which fills the data variable (this works fine)
foreach (JObject incentive in data["incentives"])
{
// Add finance rate incentives
if ((string)incentive["categoryDescription"] == "Finance Rate")
{
// Add Chrome Incentive to Finance Rate
var inc = new ChromeIncentive();
inc.Group = (string)incentive["groupAffiliation"];
inc.Ownership = (string)incentive["previousOwnership"];
inc.ID = (int)incentive["incentiveID"];
inc.Category = (string)incentive["categoryDescription"];
var rate = new ChromeRate();
rate.Incentive = inc;
vehicle.FinanceRates.Add(rate); // Error is on this line
}
}
});
thread.Start();
}
The error I get:
Additional information: Object reference not set to an instance of an object.
The line I get the error for is vehicle.FinanceRates.Add(rate);
I've looked up this error and it says it has to do with creating an empty variable. So vehicle I assume would have to be the empty variable, but I'm not sure how it would be empty considering there are no empty rows in the db and it's coming straight from the db. If I comment out vehicle.FinanceRates.Add(rate);
then it works fine pulling all of the vehicles with their data.
Any idea what's wrong in my code that could be causing this error? Perhaps the thread prevents it from editing the variable which is outside of the thread?
What the code should do:
Pull a list of unique vehicles from the db. Loop those vehicles and run an API call for each one in a different thread. Take the API data and add it to the vehicle data.
I've even tried checking if null and still I get the error:
if (vehicle != null && rate != null)
{
vehicle.FinanceRates.Add(rate);
}
I'm thinking it has to do with Threads but what about Threads would cause that error?