Dav*_*d M 2 c# linq dbnull casting
Linq的新手,如果这是基本的,请道歉.此查询抛出错误{"无法将DBNull.Value强制转换为'System.Int64'.请枚举结果时使用可空类型."}.
private void AddLevels(long rootid)
{
var results = from row in data.AsEnumerable()
where row.Field<long>("ParentID") == rootid
select row;
foreach (DataRow row in results)
{
//do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
列ParentID确实接受空值 - 我需要单独处理这些吗?
EDIT2:下面的实际解决方案仍然使用Linq.
编辑:我通过废除Linq并仅使用DataTable.Select语句解决了这个问题.如果有人对性能差异有所了解我会感兴趣.
Don*_*nut 13
在查询中使用此行:
where row.Field<decimal?>("ParentID") == rootid
Run Code Online (Sandbox Code Playgroud)
decimal?是语法糖System.Nullable<decimal>,它基本上是相同的decimal,除了它还允许null值.
long 是一个完全不同的类型 - 它只能表示整数而不是十进制值,因此"指定的强制转换无效"错误.