2009-10-14 26 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