Oracle 数据提供程序的奇怪行为(错误)(InvalidCastException:指定的转换无效)

Strange Behavior (Bug) of Oracle Data Provider (InvalidCastException: Specified Cast is not Valid)

Oracle ManagedDataAccess 似乎有问题,如果您尝试执行以下示例,您可能会遇到错误(这是意外的;更改为其他字段但相同的数据类型可能不会导致问题);尽管 entity framework 已经毫无问题地实现了查询:

INVENTORY
.GroupBy(inv => 1)
.Select(invGroup => new 
{
    GrossWeight = invGroup.Sum(inv => inv.GROSS_WEIGHT / inv.BASE_QTY_PER_UNIT)
})

前面的代码会导致以下异常:

   InvalidCastException
   Specified cast is not valid. 
   StackTrace
   at Oracle.ManagedDataAccess.Client.OracleDataReader.GetDecimal(Int32 i)
   at Oracle.ManagedDataAccess.Client.OracleDataReader.GetValue(Int32 i)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
   at lambda_method(Closure , Shaper )
   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
   at UserQuery

网上搜了一下,好像其他人也有这个异常 https://chrismay.org/2015/07/30/bug-in-oracledatareader-causing-invalidcastexception/

有两种解决方法:

选项#1 将所需值转换为 float

INVENTORY
.GroupBy(inv => 1)
.Select(invGroup => new 
{
    GrossWeight = invGroup.Sum(inv => (float)inv.GROSS_WEIGHT / (float)inv.BASE_QTY_PER_UNIT)
})

选项#2 使用 AsEnumerable() 在内存中执行求和,如下所示

INVENTORY
.GroupBy(inv => inv.BASE_QTY_PER_UNIT)
.Select(invGroup => new 
{
    GrossWeight = invGroup.Sum(inv => inv.GROSS_WEIGHT),
    BaseQuantityPerUnit = invGroup.Key
})
.AsEnumerable()
.Select(anony => new
{
    GrossWeight = anony.GrossWeight / anony.BaseQuantityPerUnit
})