Search code examples
c#linq.net-core

How search only in records that have value (LINQ)


I have this part of code:

int[] toRemoveInChildHotelOffersMealsIds = _hotelOfferDetailsRepository.Get()
                .Where(x => toRemoveHotelOfferMealsIds.Contains(x.ParentId.Value))
                .Select(x => x.ID)
                .ToArray();

This code must return child ids to remove if exist.

And this section throws an error

Nullable object must have a value

in unit tests. And second thing I don't understand why I don't get the same exception during real work.

So how can I modify my code to avoid this exception and search only in records that have a value?


Solution

  • This might be because the value of ParentId is resolved to null and ParentId.Value throws and exception. Are you setting a value for ParentId where the data is mocked?

    To avoid this, do a null check (assuming the ones that doesn't have a ParentId value must be ignored)

    int[] toRemoveInChildHotelOffersMealsIds = _hotelOfferDetailsRepository.Get()
                        .Where(x => x.ParentId.HasValue ? toRemoveHotelOfferMealsIds.Contains(x.ParentId.Value) : false)
                        .Select(x => x.ID)
                        .ToArray();
    

    If they need to be considered, then use

    int[] toRemoveInChildHotelOffersMealsIds = _hotelOfferDetailsRepository.Get()
                        .Where(x => !x.ParentId.HasValue || toRemoveHotelOfferMealsIds.Contains(x.ParentId.Value))
                        .Select(x => x.ID)
                        .ToArray();