When I run the following Linq:
var selectedProduct = db.Products.FirstOrDefault(a => a.ProductNr == productNr)?.Id; model.PackTypes = db.Zones .Where(az => az.ProductId == selectedProduct && az.StoragePrio > 0) .ToList() .DistinctBy(p => p.PackType) .OrderBy(x => x.PackType) .Select(x => new DropdownItemViewModel<int> { Id = (int)x.PackType, Name = x.PackType.Translate() }); return true; I get this error:
System.InvalidOperationException: 'Nullable object must have a value.' on this code Id = (int)x.PackType,
Now I know I must do a nullcheck so I have tried this:
if (x.PackType != null) return new DropdownItemViewModel<int> { Id = (int)x.PackType, Name = x.PackType.Translate() }; return null; Still doesn't work, by that I mean I still have problem with NullCheck.
az.ProductIdbenullat some point? If not, why are you doing that query at all vs just exiting early ifselectedProduct == null?.Where(az => az.ProductId == selectedProduct && az.StoragePrio > 0 && az.PackType != null)to filter out any entries whereaz.PackType == null. Unless there's something else that is null here?Wheredon't useToListbutAsEnumerable. On that way you don't load all into memory at once but you can use deferred execution.