【问题标题】:Return entity that has highest/lowest value in the related entity返回相关实体中具有最高/最低值的实体
【发布时间】:2014-03-24 20:53:25
【问题描述】:

如何从相关实体中查找最高或最低值? 我试图将 LINQ/lambda 与导航属性一起使用,但遇到了 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

有数据,案例举例

员工

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

汽车

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

员工和汽车一对一的关系。

在寻找最高价值时,我需要从查询中获取员工“John”。 在寻找最低价值时,我需要“史蒂夫”。 car_age 在数据库中也可以为空。

在调用上述方法之前,使用以下方法从数据库中检索实体:

Dim query = From e In _context.employees.Include("car")
            Select e

【问题讨论】:

  • NullReferenceExceptionStackTrace 值是多少?
  • 在 MyNS.MyModel.company._Lambda$__41(employee x) in C:/Temp... 在 System.Linq.EnumerableSorter2.ComputeKeys(TElement[] elements, Int32 count) at System.Linq.EnumerableSorter1.Sort(TElement[] 元素,Int32 计数) 在 System.Linq.OrderedEnumerable1.<GetEnumerator>d__0.MoveNext() at System.Linq.Enumerable.First[TSource](IEnumerable1 源) 在 MyNS.MyModel.company.get_OldestCar()

标签: .net linq entity-framework lambda navigation-properties


【解决方案1】:

堆栈跟踪表明您的员工没有汽车。您确定您拥有的唯一数据就是您在帖子中显示的数据吗?

如果您尝试这样做会发生什么:

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

应用程序是否仍然崩溃?如果没有,那你的问题是:有些员工没有车。

【讨论】:

  • 这样我得到了 InvalidOperationExceltion (序列不包含任何元素)。员工没有车并且 car_id 可以为 Null 是可能且可以接受的。
  • @user2143213 啊,那么你的员工没有个现在看来有车了! :) 我编辑了我的答案,看看。
  • 在失败的情况下,是的,没有一个员工有车。 FirstOrDefault 是解决方案。
【解决方案2】:

我想你会想要这样的东西:

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()

【讨论】:

  • 在 VB.NET 这有效: Dim e As employee = Me.employees.Where(Function(x) x.car IsNot Nothing).OrderBy(Function(x) x.car.car_age.GetValueOrDefault (1000)).First() 但如果我使用 Where(Function(x) x.car.car_age IsNot Nothing 那么我会遇到相同的 NullReferenceException。
  • ...但是如果所有的 car_id 都是 Null 的则不起作用 -> InvalidOperationException(序列不包含任何元素)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多