c# - LINQ 查询中的 InvalidCastException

标签 c# linq linq-to-sql .net-3.5 exception-handling

对于此 LINQ 查询,我得到以下异常:

(from row in ds.Tables[0].AsEnumerable()
 where row.Field<string>("Dept_line_code") == DeptCode &&
 row.Field<string>("Skill_Name") == skill &&
 row.Field<string>("Acct_Code") == account && row.Field<string>("Location") == dtNewTable.Rows[intRow]["Location"].ToString()
 select row.Field<int>("Presently_Available") == null ? 0 : row.Field<int>("Presently_Available")
).FirstOrDefault();

异常信息:

Exception type: InvalidCastException

Exception message: Cannot cast DBNull.Value to type 'System.Int32'. Please use a nullable type.

我不知道可空类型,也不知道如何使用可空类型来克服此异常。

最佳答案

你必须让 int 接受空值 => int?

row.Field<int?>("Presently_Available") == null ? 0 : row.Field<int>("Presently_Available") ;

这是一个link对于可空类型

关于c# - LINQ 查询中的 InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8803977/

相关文章:

linq - 在 Linq 投影中设置 EntityCollection

GROUP BY WITH ROLLUP 的 LINQ to SQL 版本

c# - 查找终端服务用户的文档文件夹

c# - IOException 被 ReaderWriteLockSlim 抛出?

c# - 查看可空类型是否有值的最简洁方法是什么,如果有,将该值与另一个不可空类型的值进行比较?

c# - 具有整数值的下拉列表上的 ASP.NET mvc 验证标签?

c# - 从 Entity Framework 中的集合加载相关实体

c# - 确定两个集合是否共享至少一个元素

c# - LINQ to SQL 添加 CASE 语句,然后原始字段未找到

wpf - 什么可能导致 db.SubmitChanges() 在 linq-to-sql 中不起作用?