I'm using EF Core 3.0 code first. I have this loop:
foreach (var profileCount in quantity)
{
//here I get the exception:
var oldItem = dc.Stock.Items.FirstOrDefault(a => a.Profile.Id == profileCount.Key);
if (oldItem == null)
{
dc.Stock.Items.Add(new Item
{
Price = 0,
ProfileId = profileCount.Key,
Quantity = profileCount.Value,
WasChanged = false
});
}
}
Stock.Items
is empty(not null). First iteration works fine, on the second one I get
System.NullReferenceException: Object reference not set to an instance of an object.
I guess it's because I add and try to read from the same collection, but I'm not sure why exactly this is happening.