문제

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
도움이 되었습니까?

해결책

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.

다른 팁

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()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top