First, Thomas Levesque had a good solution for ordering fields in a related table where the relation may not always be there:
userQuery = userQuery.OrderBy(u =>
(u.Department != null) ? u.Department.Name : String.Empty);
I need to do the same thing. My aggregate root is enormous:
myQuery = myQuery.OrderBy(p =>
(p.Seconds == null
? 0
: p.Seconds.FirstOrDefault() == null
? 0
: p.Seconds.First().Thirds == null
? 0
: p.Seconds.First().Thirds.FirstOrDefault() == null
? 0
: p.Seconds.First().Thirds.First().Forths == null
? 0
: p.Seconds.First().Thirds.First().Forths.FirstOrDefault() == null
? 0
: p.Seconds.First().Thirds.First().Forths.First().myField));
Is this really the way to do this, or is there something much easier to read? My other problem is that the nested myField has a matching "default" value sitting in the top level Query, also named by myField. The idea was to Order by the coalesce of these two fields (??).
Edit: I think this would include the "default value" from the first field:
myQuery = myQuery.OrderBy(p =>
(p.Seconds == null
? p.myDefaultField // Used to be zero
: p.Seconds.FirstOrDefault() == null
? p.myDefaultField
: p.Seconds.First().Thirds == null
? p.myDefaultField
: p.Seconds.First().Thirds.FirstOrDefault() == null
? p.myDefaultField
: p.Seconds.First().Thirds.First().Forths == null
? p.myDefaultField
: p.Seconds.First().Thirds.First().Forths.FirstOrDefault() == null
? p.myDefaultField
: p.Seconds.First().Thirds.First().Forths.First().myField));
How could I rewrite this OrderBy to be cleaner? This code fails with an error of "Cannot compare elements of type 'System.Collections.Generic.IEnumerable`1'. Only primitive types (such as Int32, String, and Guid) and entity types are supported."