1

When I use EF Core linq query, and order the list by inner object's property. If the inner object is null, it will not throw exception.

  • For example:

    var Posts = await context.Post
       .Where(p => p.BlogId == 1))
       .Include(p => p.Author)
       .OrdeyBy(p => p.Author.Name)
       .ToListAsync();
    

If one of Author in Post is null, the query still can be executed successfully.

But if I order a list, which is not query by EF Core. For example, I order an existing list Posts:

Posts.OrderBy(p => p.Author.Name).ToList()

It will throw a null reference exception. Like this metioned: Check object null inside orderby Linq

What make their different? Why EF Core linq order is not impact by null reference?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
Daisy
  • 21
  • 1
  • The ToList() is causing the exception. So remove the ToList(). Do it in two steps 1) var orderedResults = Posts.OrderBy(p => p.Author.Name); 2) If(orderedResults.Count() > 0) orderedResults = OrderResults.ToList(); – jdweng Jul 28 '23 at 14:31
  • you can try `Posts.OrderBy(p => p.Author?.Name).ToList()` – jeb Jul 28 '23 at 14:31
  • The difference is that in first example you load related data - Author, in second - you don't. – Max Naumov Jul 28 '23 at 14:32
  • 2
    The first one is turned into a Sql Statement and executed on the database. The orderby expression never actually executes in your c# process, it is turned into a store sql expression and executes against your database as a query. The other example is executed in memory as code and runs in your c# process which would result in an NRE if the object instance was null. – Igor Jul 28 '23 at 14:32

0 Answers0