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吧。

原创粉丝点击