-1

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.

DavidG
  • 113,891
  • 12
  • 217
  • 223
Jamil
  • 830
  • 2
  • 15
  • 34

1 Answers1

1

When you insert your first item (dc.Stock.Items.Add(new Item) you don't add a Profile, so on the next iteration a.Profile.Id will be a NullReferenceException.

Either assign a Profile when you add a new item, or check for null in your FirstOrDefault.

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35