Linq to DataTable - Cannot cast DBNull

久未见 提交于 2019-11-28 10:42:54

问题


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
        }

    }

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

EDIT2: Actual solution below that still uses Linq.

EDIT: 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.


回答1:


Use this line in your query:

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

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

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




回答2:


long rootid is nullable type? It should be then only it can accept nulls



来源:https://stackoverflow.com/questions/7091379/linq-to-datatable-cannot-cast-dbnull

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!