映射数据类型Oracle和C#时出错

时间:2018-04-28 06:44:30

标签: c# oracle

我有一个ID NUMBER(18)的表,我有一个属性为public Int64 ID { get; set; }的类,用于映射ID形式C#与Oracle。

我的表定义

enter image description here

但是当我得到这样的最大ID时,我有一个错误:

  1. 运行查询

    SELECT MAX(ID) ID FROM MYTABLE
    

    系统抛出错误:

      

    “类型'System.Decimal'的对象无法转换为'System.Int64'类型。”

  2. 但是当我运行这样的查询时:

    SELECT ID FROM(
                    SELECT ID FROM MYTABLE ORDER BY ID DESC
                  ) WHERE ROWNUM =1
    

    没关系。

  3. 我不知道为什么(1)抛出错误,为什么(2)完成?

    datatype(1)和(2)有什么区别?

1 个答案:

答案 0 :(得分:4)

可能的情况1:

我猜你表中有NULL个值(所以你的两个查询都不相同):

SELECT MAX(ID) ID FROM T_00_RQMM  -- aggregate func ignore NULLS

可是:

SELECT ID FROM(SELECT ID FROM T_00_RQMM ORDER BY ID DESC) WHERE ROWNUM = 1;  
-- NULL is the max value

<强> DBFiddle Demo

无论如何你应该尝试映射:

using System.Numerics;
...
public BigInteger ID { get; set; }

修改

可能的方案2:

数据类型可能有问题(然后使用显式CAST):

SELECT CAST(MAX(ID) AS NUMBER(18,0)) ID FROM T_00_RQMM 

<强> DBFiddle Demo 2

完整演示:

CREATE TABLE T_00_RQMM (ID NUMBER(18,0));
INSERT INTO T_00_RQMM VALUES(NULL);
INSERT INTO T_00_RQMM VALUES(100);

CREATE TABLE t1 AS SELECT MAX(ID) ID FROM T_00_RQMM;

CREATE TABLE t2 AS SELECT ID FROM(SELECT ID FROM T_00_RQMM ORDER BY ID DESC) 
                                  WHERE ROWNUM = 1;

CREATE TABLE t3 AS SELECT CAST(MAX(ID) AS NUMBER(18,0)) ID FROM T_00_RQMM;


SELECT TABLE_NAME, COLUMN_NAME, DATA_PRECISION, DATA_SCALE
FROM all_tab_cols
where table_name in ('T1', 'T2', 'T3')
ORDER BY Table_name;

输出:

+------------+-------------+----------------+------------+
| TABLE_NAME | COLUMN_NAME | DATA_PRECISION | DATA_SCALE |
+------------+-------------+----------------+------------+
| T1         | ID          | null           | null       |
| T2         | ID          | 18             | 0          |
| T3         | ID          | 18             | 0          |
+------------+-------------+----------------+------------+