c# - DataSet 自动生成的代码抛出 StrongTypingException
问题描述
(我在提出问题时遇到了很多麻烦,所以我尽力而为。我确实知道一种解决方法,但是每次我更改 SQL 结构中的某些内容(例如添加一列)时,我都必须更改myDataSet.Designer中的自动生成代码。)
——一些背景;我在 2008 年学习了 C# 数据库的东西,所以我可能会用老式的方式来做,我只是一个偶尔的程序员..
我的工作流程:
- 在 MS SQL 管理中创建数据库
- 用 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 中的自动生成代码来解决这个问题,我认为这是同一种问题。我似乎无法复制这个问题,如果这不能解决问题,我可能会提出一个新问题。
这个问题可能已经回答了,但是在寻找答案很长一段时间后我没有找到解决方案(我明白吗?哈哈)。
(我是这个网站的长期读者,发现了很多帮助,但从来不需要问问题)
解决方案
推荐阅读
- python - 拆分为具有特定行属性值的训练集和测试集
- amazon-web-services - cloudfront 给出“您的连接不是私有的”错误
- python - Groupby into list for non consecutive values
- arrays - 无法设置未定义的属性“元素” - Angular中的数组
- javascript - 使用 JavaScript 更改可见性时如何使用过渡/动画?
- python - 在 VS Code Insiders for Python Native Notebook 中哪里可以找到数据查看器/变量资源管理器?
- reactjs - 反应 CRA 代理问题
- c# - 将自定义类型作为命令参数传递
- postgis - 完整的新手问题:我想通过命令提示符删除一个表(postgis)
- reactjs - 如何在反应 js 中模拟嵌套组件导入并使用反应测试库进行测试