Question

How to look for the highest or lowest value from the related entity? I was trying to use LINQ/lambda with a navigation property but run into a NullReferenceException.

Dim e As employee = Me.employees
       .OrderBy(Function(x) x.car.car_age.GetValueOrDefault(1000))
       .First()

If e IsNot Nothing Then Return e.car.car_age

With data, the case example

employee

id  name   car_id
1   John   1
2   Mark   2
3   Steve  3

car

id  car_age
1   15
2   [Null]
3   8
4   19
5   3

employee and car 1-to-1 relationship.

When looking for highest value, I need to get employee "John" from the query. When looking for lowest value, I need "Steve". car_age can also be null in the database.

Berfore calling the above, the entities were retrieved from the database using:

Dim query = From e In _context.employees.Include("car")
            Select e
Was it helpful?

Solution

The stack trace suggests you have employees without cars. Are you certain the only data you have is the one you shown in your post?

What happens if you try this instead:

Dim e As employee = Me.employees
    .Where(Function(x) x.car IsNot Nothing)
    .OrderBy(Function(x) x.car.car_age.GetValueOrDefault(1000))
    .FirstOrDefault()

Does the app still crashes? If not then there's your problem: some employee just don't have a car.

OTHER TIPS

I think you'd want something like:

Dim e As employee = Me.employees
   .Where(Function(x) x.car.car_age IsNot Nothing)
   .OrderBy(Function(x) x.car.car_age.GetValueOrDefault(1000))
   .First()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top