Test Null after FirstOrDefault

c# entity-framework-core linq

Question

I have the following Linq expression in EntityFrameworkCore:

var models = await products.Select(product => new ProductModel {
  Id = product.Id,
  ProductType = new ProductTypeModel {
    Id = product.ProductType.Id,
    Name = product.ProductType
             .ProductTypesI18N
             .FirstOrDefault(y => y.LanguageCode == languageCode)?.Name
  }
}.ToListAsync()

I get the following error:

An expression tree lambda may not contain a null propagating operator.

It there a short way to not fire an error if FirstOrDefault returns null?

Note:
I think that might be a better way instead of using FirstOrDefault.
For example, in the following code line: new ProductTypeModel {

1
0
2/15/2019 9:42:40 PM

Accepted Answer

Select the Name of the ProductType that you want before your FirstOrDefault:

Name = product.ProductType.ProductTypesI18N
         .Where(productType => productType.LanguageCode == languageCode)
         .Select(productType => productType.Name)
         .FirstOrDefault(),

Simple comme bonjour!

1
2/18/2019 12:12:29 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow