Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query works with null but not int? in where clause

I have a linq query function like (simplified):

public IList<Document> ListDocuments(int? parentID)
{
    return (
        from doc in dbContext.Documents
        where doc.ParentID == parentID
        select new Document
        {
            ID = doc.ID,
            ParentID = doc.ParentID,
            Name = doc.SomeOtherVar
        }).ToList();
}

Now for some reason when I pass in null for the parentID (currently only have data with null parentIDs) and I get no results.

I copy and paste this query into LinqPad and run the following:

from doc in dbContext.Documents
where doc.ParentID == null
select doc

I get back a result set as expected...

The actually query has left join's and other joins but I have removed them and tested it and get the same result so the joins are not affecting anything. The app and LinqPad are both connected to the same DB as well.

Edit: Tested with just 'null' in the appliction query and it returns the result as expected so the issue is using null vs int?. I have updated question to make it more useful to others with the same issue to find this thread.

like image 355
Kelsey Avatar asked Jul 28 '09 15:07

Kelsey


People also ask

How do you handle NULL values in LINQ query?

An object collection such as an IEnumerable<T> can contain elements whose value is null. If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c !=

What does LINQ return when the results are empty?

It will return an empty enumerable.

Is NULL in LINQ to SQL?

In SQL Server, a SQL statement like 'NULL=NULL' evaluates to false. however 'NULL IS NULL' evaluates to true. So, for NULL values in your database columns, you need to use the 'IS' operator instead of the regular '=' operator.


1 Answers

Literal null values are handled differently than parameters which could be null. When you explicitly test against null, the generated SQL will use the IS NULL operator, but when you're using a parameter it will use the standard = operator, meaning that no row will match because in SQL null isn't equal to anything. This is one of the more annoying .NET/SQL semantic mismatches in LINQ to SQL. To work around it, you can use a clause like:

where doc.ParentID == parentID || (doc.ParentID == null && parentID == null)
like image 137
kvb Avatar answered Oct 21 '22 11:10

kvb