tags:

views:

2461

answers:

3

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.

A: 

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)
dmo
The error happens as soon as I fetch the first value which contains a DBNull. So varActiveAndUsedElementsWithDetails.First() could produce it. The method d.IsRemarkNull() is auto-generated on the dataset and calls the System.Data.DataRow.IsNull() method: "return this.IsNull(this.tableDetails.RemarkColumn);"
Marc
dmo
Yes they are treated separately, that's why you can't test d.Remark == null. However the generated method.IsRemarkNull() should exactly handle this situation, but here it doesn't seem to work...
Marc
I found out that the problem was in fact a null reference exception because 'd' was null. So calling d.IsRemarkNull() resulted in this null reference exception. Thanks a lot for your help anyway.
Marc
A: 

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

Ada
Thanks for the hint but the field does allow NULL in the db. Also the typed datatable field does allow NULL. That's why it has this auto-generated d.IsRemarkNull() method btw.
Marc
+2  A: 

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