oracle对象不能从 dbnull 转换为其他类型,对象不能从DBNull转换为其他类型。读取器读取空值时出错...

我喜欢使用DataTable而不是DataReader。我讨厌重复的样板,所以我在DataRow类中添加了一些扩展方法来封装downcast逻辑并使代码更具可读性:

DataTable dt = ExecStoredProcedure() ;

foreach ( DataRow dr in dt )

{

int id = dr.CastAsInt("id") ;

dateTime? dtLastUpdated = dr.CastAsDateTimeNullable("last_update_date") ;

int? col3 = dr.CastASIntNullable(3) ;

}这里是将DataRow中的列值向下转换为int / int?的代码:

#region downcast to int

public static int CastAsInt( this DataRow row , int index )

{

return toInt( row[index] ) ;

}

public static int CastAsInt( this DataRow row , string columnName )

{

return toInt( row[columnName] ) ;

}

public static int? CastAsIntNullable( this DataRow row , int index )

{

return toIntNullable( row[index] );

}

public static int? CastAsIntNullable( this DataRow row , string columnName )

{

return toIntNullable( row[columnName] ) ;

}

#region conversion helpers

private static int toInt( object o )

{

int value = (int)o;

return value;

}

private static int? toIntNullable( object o )

{

bool hasValue = !( o is DBNull );

int? value = ( hasValue ? (int?) o : (int?) null ) ;

return value;

}

#endregion conversion helpers

#endregion downcast to int我确定从DataReader挂起类似的扩展方法会相当简单。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值