I get a message about a possible correct NullReferenceException.
It is not clear which system generates this message. Resharper?
In any case, in this case, if it is really LINQ for Entities, the warning is false. LINQ to Entities in many cases performs automatic "deep zero collapse", and this is one such case.
In the original request:
var articles = context.Articles .Where(a => a.Id != articleId) .OrderBy(p => p.Categories .OrderBy(q => q.Name) .FirstOrDefault() .Name) .ToList();
... there will be no NullReferenceException
if the article does not have a category associated with it. Instead, the ordering value will be taken as null
for such articles (this means that articles in which there are no categories at all will be displayed first), and this looks exactly the way you want. Therefore, no additional effort is required on your part!
Note that with other LINQ providers (such as LINQ to Objects), the behavior can be completely different, and .FirstOrDefault().XXX
indeed a risky expression.
On the other hand, prematurely optimize. If you already have a working solution, compare it. If this is too slow, find out why - in this case the keys are in the generated SQL. LINQ to Entities query optimizer can often be smarter than you think. :)
source share