首页 > 解决方案 > DataSet 自动生成的代码抛出 StrongTypingException

问题描述

(我在提出问题时遇到了很多麻烦,所以我尽力而为。我确实知道一种解决方法,但是每次我更改 SQL 结构中的某些内容(例如添加一列)时,我都必须更改myDataSet.Designer中的自动生成代码。)

——一些背景;我在 2008 年学习了 C# 数据库的东西,所以我可能会用老式的方式来做,我只是一个偶尔的程序员..

我的工作流程:

我的工作流程是错误的还是过时的?(我可能跳过了一些步骤,但我想你明白了)

- 问题; 现在到目前为止一切正常,当我尝试使用查询读取包含 DBNull 值的整数或十进制数据时会出现问题

喜欢:

        public decimal GetAnimalWeight(int animalId)
        {
            var query = from a in this.myDataSet.Animals
                        where a.Id == animalId
                        select a.Weight;

            return Convert.ToDecimal(query.ToList()[0]);
        }

我发现异常是在查询中引发的,而不是在 Convert.ToDecimal() 中。所以我能做的不多。

异常发生在myDataSet.Designer自动生成的代码中:

            [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
            public decimal Weight {
                get {
                    try {
                        return ((decimal)(this[this.tableAnimals.WeightColumn]));
                    }
                    catch (global::System.InvalidCastException e) {
                        throw new global::System.Data.StrongTypingException("The value for column \'Weight\' in table \'Animals\' is DBNull.", e);
                    }
                }
                set {
                    this[this.tableAnimals.WeightColumn] = value;
                }
            }

我的解决方法:(每次 DataSet 更改时,我都必须对所有整数和小数执行此操作):

            [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
            [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "16.0.0.0")]
            public decimal Weight {
                get {
                    try {
                        return ((decimal)(this[this.tableAnimals.WeightColumn]));
                    }
                    catch (global::System.InvalidCastException e) {
                        return (decimal)this.tableAnimals.WeightColumn.DefaultValue;
                        // I leave next line alone since it is not executed and its the original code:
                        throw new global::System.Data.StrongTypingException("The value for column \'Weight\' in table \'Animals\' is DBNull.", e);
                    }
                }
                set {
                    this[this.tableAnimals.WeightColumn] = value;
                }
            }

奇怪的是我不记得过去有这个问题,不知道我做错了什么。在 SQL 中更改小数精度后我也遇到了问题,因为我还通过更改 DataSet 中的自动生成代码来解决这个问题,我认为这是同一种问题。我似乎无法复制这个问题,如果这不能解决问题,我可能会提出一个新问题。

这个问题可能已经回答了,但是在寻找答案很长一段时间后我没有找到解决方案(我明白吗?哈哈)。

(我是这个网站的长期读者,发现了很多帮助,但从来不需要问问题)

标签: c#sql-serverdatasetdbnull

解决方案


推荐阅读