【问题标题】:VB.NET LINQ to EF Sum Function Error when no records returned没有返回记录时的 VB.NET LINQ to EF Sum 函数错误
【发布时间】:2012-06-01 02:37:24
【问题描述】:

看过一些 C# 的解决方案,但不知道如何在 VB.NET 中解决问题。

查询:

Dim Query = (From t In myEntities.Bookings
Where(t.Ref = Someid)
Select t.People).Sum()

t.Ref 字段是 Intt.People 也是。

SomeId 值是相关表的主键。这个问题是Bookings 表中并不总是有 Ref 值为 Someid 的记录 - 因此查询会引发以下错误。

我已经看到其他人通过捕获错误解决了这个问题,但是通过阅读这个并根据错误信息,似乎应该有一个解决方案(在 VB.NET 中)来转换查询或一些查询中的字段为可空类型?

错误如下:

The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.

【问题讨论】:

    标签: vb.net linq-to-entities


    【解决方案1】:

    您的 Sum() 正在处理整数,而您真正想要的是一个可为空的整数。

    Dim Query = (From t In myEntities.Bookings Where(t.Ref = Someid) Select t.People).Sum(Function(x) CType(x, Integer?))

    请看这里:Linq query with nullable sum

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多