DBNull异常处理
来源:互联网 发布:淘宝汽车装饰品 编辑:程序博客网 时间:2024/05/29 16:07
今天为了偷懒不想写数据库访问操作类,而直接使用DotNet的LINQ to SQL类或者是 数据集模板,在查询数据时出现 表“Products”中列“ShipRegion”的值为 DBNull 的异常,使用 order.shipRegion = System.DBNull.Value.Equals(od.ShipRegion) ? “” : od.ShipRegion; 和 order.shipRegion = Convert.IsDBNull(od.ShipRegion) ? “” : od.ShipRegion; 均不凑效依然抛出(表“Products”中列“ShipRegion”的值为 DBNull)的异常信息,十分郁闷.然后上网搜索一番,试过N种方案,问题依然存在.因为在代码中加入了捕获异常,所以调试时直接显示该异常信息.很想把数据集删除然后手工写数据库访问操作类,但又不死心啊,因为从来就是手工写,而第一次使用就出问题,心里太不爽了.为了能在调试中找到问题代码,所以将try catch代码删除后进行调试,结果发现这个异常信息在是 数据集 类的设计代码中抛出的,将抛出异常代码删除改为return “”(因为数据库中的值是Null,而显示给客户的信息就应该为空串,所以就直接返回空串),再调试程序时,问题得以解决.
同时悟出try catch在某些情况下会隐藏真实的问题.以下是我遇到問題中的部分代碼
文件名:NorthwindData.designer.cs
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public string ShipRegion {
get {
try {
return ((string)(this[this.tableProducts.QuantityPerUnitColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("表“Orders”中列“ShipRegion”的值为 DBNull。", e);
}
}
set {
this[this.tableOrders.ShipRegionColumn] = value;
}
}
修改為
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public string ShipRegion {
get {
try {
return ((string)(this[this.tableProducts.QuantityPerUnitColumn]));
}
catch {
retrun “”;
}
}
set {
this[this.tableOrders.ShipRegionColumn] = value;
}
}
或
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public string ShipRegion {
get {
try {
return ((string)(System.DBNull.Value.Equals( (this[this.tableOrders.ShipRegionColumn])) ? "": (this[this.tableOrders.ShipRegionColumn])));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("表“Orders”中列“ShipRegion”的值为 DBNull。", e);
}
}
set {
this[this.tableOrders.ShipRegionColumn] = value;
}
}
若不想用以上方法,那就使用 DBNull.Value.Equals() 来判断是否为DBNull吧。
- DBNull异常处理
- DBNull
- DBNULL
- 防止DBNull 造成类型转换异常
- .net 中统一处理 Nothing DbNull Empty
- 因DataTable的字段值为DBNull引发的异常
- C#中如何处理DBNull?是不是数据库设计问题?
- Oracle中Integer类型/DBNull的处理方法
- 异常处理+异常+处理异常+自定义异常
- 异常详细信息: System.InvalidCastException: 对象不能从 DBNull 转换为其他类型。
- 异常详细信息: System.InvalidCastException: 对象不能从 DBNull 转换为其他类型——的解决方法
- C# 异常"关于对象不能从DBNull转换为其他类型"
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- 异常处理
- search_n
- Linux下调试core dump 文件的方法
- QT Graphics View 框架
- 关于linux下访问寄存器
- Oracle Minus关键字
- DBNull异常处理
- eclipse搭建hadoop开发环境
- DWR框架配置入门
- <authentication mode="Forms"> 发布错误
- I2C协议
- 1:(C#下使用GDAL库)下载和引用方法
- U-Boot-2010.12移植到2440 .
- android:textAppearance解析
- ASP+MYSQL:ODBC 驱动程序不支持所需的属性