Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check null value in linq to sql

Tags:

c#

linq-to-sql

I am trying to use following linq to sql query to get result. But it doesn't works if parentCategoryId passed as null

 public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
    {
        var categories = from c in source where c.ParenCategoryId == parentCategoryId select c;
        return categories;
    }   

but following works if null used directly in place of parentCategoryId

 public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
    {
        var categories = from c in source where c.ParenCategoryId == null select c;
        return categories;
    }
like image 729
Suresh Maurya Avatar asked May 05 '12 09:05

Suresh Maurya


People also ask

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.

Can LINQ return NULL?

in conclusion no, it won't return null since null can't say sequence contains no elements it will always say object reference not set to an instance of an object ;) Oh, your explanation helps further understanding.

How do I check if a list is NULL in SQL?

randomid = trand.id where @ids IS NULL OR t.id IN (select item from dbo. ufnSplit(@ids,',')); So if it's NULL it will return everything, otherwise it will evaluate the OR part of the WHERE clause.

Is LINQ converted to SQL?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.


1 Answers

You can use object.Equals, it will match on null values also.

public static IEnumerable<Category> GetChildren(this Table<Category> source, int? parentCategoryId)
{
    var categories = from c in source 
                     where object.Equals(c.ParenCategoryId, parentCategoryId) 
                     select c;
    return categories;
} 
like image 189
Magnus Avatar answered Sep 28 '22 09:09

Magnus