2009-10-14 28 views
0

我不斷收到錯誤System.InvalidCastException:指定的轉換無效。在運行期間。 RewardJoinType在數據庫中可以爲null。可空的Enum轉換爲Int16

這是代碼行轉換失敗:

c.rewardJoinType = (RewardJoinType)reader.GetInt16(); 

'reader.GetInt16()' 投擲類型的異常則 '' 短{System.InvalidCastException}

在一個類中我有下面的代碼行:

private RewardJoinType? rewardJoinType; 

...一些其他的代碼

c.rewardJoinType = (RewardJoinType?)reader.GetInt16(); 

...一些其他的代碼

conn.AddParam("@rewardJoinType", (int?)rewardJoinType); 

...一些其他的代碼

public RewardJoinType? RewardJoinType 
{ 
    get { return rewardJoinType; } 
    set { rewardJoinType = value; } 
} 

而這裏的枚舉本身

public enum RewardJoinType 
{ 
    Auto, 
    Manual 
} 

是因爲通過默認枚舉是Int32甚至t hough我有它可以爲空它不能夠投出一個空Int16?

我們處理的DBNull爲Int16的,像這樣已經在我們的讀者:

public short GetInt16() 
    { 
     columnIndex++; 
     return reader.IsDBNull(columnIndex) ? (short)0 : reader.GetInt16(columnIndex); 
    } 
+0

InvalidCastException在哪裏被拋出?哪一行代碼?以及它試圖從和來自哪裏? – thecoop 2009-10-14 13:43:28

+0

已更新。它只會在異常中表示無效投射。我沒有得到內心的例外。往上看。 – PositiveGuy 2009-10-14 13:46:22

+0

啊,我已經把這個領域作爲DB中的TinyInt。 – PositiveGuy 2009-10-14 13:51:48

回答

5

當數據庫值爲空,你實際得到的回覆是DBNull的,而不是「空」的一個實例,併爲DBNull不能被轉換爲其他任何東西。我爲這些情況所做的是編寫一個幫助器方法,將GetXXX()的返回值轉換爲null或可爲空的結構體。類似於:

static T? ConvertIfNotDBNull<T>(object o, Converter<object, T> converter) where T : struct { 
     return o is DBNull ? (T?)null : converter(o); 
    } 

並且您傳遞Convert.ToInt32或類似的轉換器。

如果您使用附加的調試器運行它,可以找到確切的位置,然後查看它正在嘗試向哪個方向投射。

+0

更新的原文,看看我們已經如何處理。 – PositiveGuy 2009-10-14 13:34:08

0

數據庫空不空的代碼,所以你需要像這樣

obj val = reader.GetValue(); 
if(val != DbNull.Value) c.RewardJoinType = (RewardJoinType)val; 
+0

查看更新後的帖子。我們通過用我們自定義的GetInt16()方法返回0來處理DBNull – PositiveGuy 2009-10-14 13:40:39

1

好吧,我錯了。閱讀器需要是GetInt8(),它將我們的代碼轉換爲返回一個字節,因爲DB字段的類型爲tinyInt

+0

@coffeeaddict:那麼這是否解決了問題? – Nils 2009-10-14 14:37:19