c# - Nullable Int 输入字符串的格式不正确

标签 c# asp.net wcf ado.net

我收到错误:

Input string was not in a correct format.

某些父 ID 可以为空。如果我评论 ParentId 就成功了,所以我知道就是那一行。

var mModel = new MyModel
{
    //non nullable
    Id = int.Parse(dr["Id"].ToString()),  
    //nullable
    ParentId = int.Parse(dr["ParentId"].ToString()),    <--- Throwing the error here
    //non nullable
    ProductService = dr["MyString"].ToString()
};

我尝试过 Convert.ToInt32() 和 TryParse() 以及事件 ToNullableInt 扩展方法,但这不起作用。

最佳答案

检查dr["ParentId"]中的数据库是否为空然后转换为 int或分配 null,如下所示:

ParentId = !dr.IsDBNull(dr.GetOrdinal("ParentId")) 
    ? dr.GetInt32(dr.GetOrdinal("ParentId")) 
    : null;

Note: The above code assumes that the ParentId variable is a nullable integer (int? or Nullable<int>.

关于c# - Nullable Int 输入字符串的格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20535087/

相关文章:

c# - 附加一个集合对象

c# - 通过打开 Excel 窗口将数据从 C# 写入 Excel 中断

jquery - asp.net从静态函数访问控件

c# - 整理声音文件

c# - 什么时候发生错误迁移( Entity Framework )

jquery - 如何在 Windows 上调整所选 jquery 下拉列表的大小

sql - Sync Framework 2.1 首次同步花费太多时间

wcf - 从 WCF Web 服务访问 HttpContext.Current

c# - 以 XML 形式获取 WCF web 服务响应

c# - Linq-to-SQL 和 WCF 服务 - 数据传输对象