Miguel Moura
Miguel Moura

Reputation: 39504

Test Null after FirstOrDefault

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 {

Upvotes: 1

Views: 411

Answers (1)

Harald Coppoolse
Harald Coppoolse

Reputation: 30512

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!

Upvotes: 2

Related Questions