LINQ to Dataset DBNULL problem / null reference ex

2019-08-23 10:24发布

问题:

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
                        };

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.

Can you help me with this?

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

回答1:

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)
                    };


回答2:

Where is the error coming from? Is it possible that it is the d.IsRemarkNull() that is causing it? What does that method look like?

Perhaps:

DBNull.Value.Equals(d.Remark)


回答3:

maybe this field doesn't allow null in db, get a default value for it, and avoid handling null values



标签: c# linq dbnull