Linq to DataTable – 无法强制转换DBNull

Linq的新手,如果这是基本的,请道歉。 此查询抛出错误{“无法将DBNull.Value强制转换为’System.Int64’。请使用可空类型。”}当我枚举结果时。

private void AddLevels(long rootid) { var results = from row in data.AsEnumerable() where row.Field("ParentID") == rootid select row; foreach (DataRow row in results) { //do stuff } } 

ParentID列确实接受空值 – 我是否需要单独处理这些?

EDIT2:下面仍然使用Linq的实际解决方案。

编辑:我通过废除Linq并仅使用DataTable.Select语句解决了这个问题。 如果有人对性能差异有所了解,我会感兴趣。

在查询中使用此行:

 where row.Field("ParentID") == rootid 

decimal? System.Nullable语法糖,它与decimal基本相同,只是它还允许null值。

long是完全不同的类型 – 它只能表示整数而不是十进制值,因此“指定的强制转换无效”错误。

long rootid是可以为空的类型? 它应该只是它可以接受空值