0

Unless it's in the Linq expression I could use the operator "?.". But since I can't use it in Linq, it's bad code writing. How can I do a deep null check?

_collection.Select(x=> new CollectionModel
{
Title = x.CollectionValues != null &&
        x.CollectionValues.Any(x => x.Amount == amount) &&
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle != null && 
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle.TranslationValues != null &&
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle.TranslationValues.Any(x => x.LanguageId == languageId) ?
        x.CollectionValues.First(x => x.Amount == amount).TranslationTitle.TranslationValues.FirstOrDefault(x => x.LanguageId == languageId).Value 
        : ""
}
)
codinges
  • 61
  • 6

1 Answers1

1

Try to do not do any null checks in LINQ to Entities query. EF should handle nulls automatically:

_collection.Select(x=> new CollectionModel
    {
        Title = x.CollectionValues!.FirstOrDefault(x => x.Amount == amount)!
            .TranslationTitle.TranslationValues!
            .FirstOrDefault(x => x.LanguageId == languageId)!
            .Value ?? ""
    }
);
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
  • Thanks to you, I learned the null-forgiving operator. But here(https://stackoverflow.com/questions/54724304/what-does-null-statement-mean) "In some (edge) cases, the compiler is not able to detect that a nullable value is actually non-nullable." gives a warning like Is this usage a problem? – codinges Jan 13 '22 at 18:16