1

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 {

Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Try encapsulating your entire expression in parenthesis or into it's own "var" variable then adding the ?.Name. Or you could use null colacing https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator – Zakk Diaz Feb 15 '19 at 21:27
  • 1
    Possible duplicate of [How to handle NULL object property with FirstOrDefault using Linq](https://stackoverflow.com/questions/38495629/how-to-handle-null-object-property-with-firstordefault-using-linq) – Callum Watkins Feb 15 '19 at 21:28
  • @ZakkDiaz null cloaking won't work, I think, because I will need to return name ... – Miguel Moura Feb 15 '19 at 21:32
  • 1
    That's odd because your null propagating operator is not part of an expression tree lambda as far as I can tell. How exactly is that query being used? Is it inside of a larger query? – juharr Feb 15 '19 at 21:35
  • @juharr Yes, it is part of a larger query. I updated my code. And thinking better I think I should not use FirstOrDefault because it loads the entire entity to memory? Maybe doing something before? – Miguel Moura Feb 15 '19 at 21:44
  • I found similar question https://stackoverflow.com/questions/44681362/an-expression-tree-lambda-may-not-contain-a-null-propagating-operator – Ondřej Kubíček Feb 15 '19 at 22:14
  • 1
    If `products` is an `IQueryable` from a DbSet you don't need to check for `null` because the query is executed as SQL which doesn't have a null reference concept. – Gert Arnold Feb 15 '19 at 22:25
  • @MiguelMoura Has your this problem solved? – TanvirArjel Feb 16 '19 at 01:29

1 Answers1

2

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!

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116