LINQ to Dataset DBNULL问题/空引用异常 [英] LINQ to Dataset DBNULL problem / null reference exception

查看:132
本文介绍了LINQ to Dataset DBNULL问题/空引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下LINQ查询,即使我测试它是否为NULL,当dtblDetail中的备注"列为null时,该查询始终会导致错误.

I have the following LINQ query which always results in an error when my "Remark" column in dtblDetail is null, even though I test if it is NULL.

var varActiveAndUsedElementsWithDetails =
                        from e in dtblElements
                        join d in dtblDetails on e.PK equals d.FK into set
                        from d in set.DefaultIfEmpty()
                        where (e.ElementActive == true)
                        select new
                        {
                            ElementPK = e.PK,
                            Remark = d.IsRemarkNull() ? null : d.Remark
                        };

错误消息是: 表'dtblDetails'中'注释'列的值为DBNull." 添加针对d.IsRemarkNull()的测试后,将引发空引用异常.

The error message was: "The value for column 'Remark' in table 'dtblDetails' is DBNull." After adding the test for d.IsRemarkNull() a null reference exception is thrown.

您能帮我吗?

我已经检查了以下网站,但除了必须测试DBNULL之外,没有发现其他有用的东西.但这不能解决我的问题.

I've already checked the following websites but didn't find anything useful other than that I have to test for DBNULL. But as said this doesn't solve my problem.

  • http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/3d124f45-62ec-4006-a5b1-ddbb578c4e4d
  • http://blogs.msdn.com/adonet/archive/2007/02/13/nulls-linq-to-datasets-part-3.aspx
  • http://www.vbforums.com/showthread.php?t=506645

推荐答案

问题是整个'd'项目为空. 因此,调用"d.IsRemarkNull()"会导致空引用异常. 以下代码解决了该问题:

The problem was that the whole 'd' item was empty. So calling 'd.IsRemarkNull()' resulted in the null reference exception. The following code fixed the problem:

var varActiveAndUsedElementsWithDetails =
                    from e in dtblElements
                    join d in dtblDetails on e.PK equals d.FK into set
                    from d in set.DefaultIfEmpty()
                    where (e.ElementActive == true)
                    select new
                    {
                        ElementPK = e.PK,
                        Remark = d == null? null : (d.IsRemarkNull() ? null : d.Remark)
                    };

这篇关于LINQ to Dataset DBNULL问题/空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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