Linq到DataTable-无法转换DBNull [英] Linq to DataTable - Cannot cast DBNull

查看:291
本文介绍了Linq到DataTable-无法转换DBNull的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

New to Linq, so apologies if this is basic. This query is throwing up the error {"Cannot cast DBNull.Value to type 'System.Int64'. Please use a nullable type."} when I enumerate the results.

    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
        }

    }

ParentID列确实接受空值-我需要分别处理它们吗?

The column ParentID does accept nulls - do I need to handle these separately?

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

Actual solution below that still uses Linq.

编辑:我通过取消Linq并仅使用DataTable.Select语句来解决此问题.如果有人对性能差异有所投入,我会很感兴趣.

I solved this by scrapping Linq and just using a DataTable.Select statement instead. If anyone's got input on the performance difference I'd be interested.

推荐答案

在查询中使用此行:

where row.Field<decimal?>("ParentID") == rootid

decimal? System.Nullable<decimal> 的语法糖,与decimal,除了它还允许null值.

decimal? is syntactic sugar for System.Nullable<decimal>, which is essentially the same as decimal, except that it also allows for null values.

long完全是另一种类型,它只能表示整数,而不能表示十进制值,因此会出现指定的转换无效"错误.

long is a different type altogether -- it can only represent integers and not decimal values, hence the "Specified cast is not valid" error.

这篇关于Linq到DataTable-无法转换DBNull的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆