Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq to sql checking for null

Tags:

linq-to-sql

my database field int_ParentId consist of a Null value . how would i check it for a null in this linq query . it is not working

  return _db.Categories.Where(m => m.int_ParentId==null);
like image 607
maztt Avatar asked Mar 07 '11 19:03

maztt


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.

Does LINQ query 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. Thank you !

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 !=


1 Answers

Have you mapped you int_ParentId database field to int? type (e.g. <Column Name="int_ParentId" Type="System.Int32" DbType="Int" CanBeNull="true" />)? If yes, both:

return _db.Categories.Where(m => m.int_ParentId == null);

and

return _db.Categories.Where(m => m.int_ParentId.HasValue);

should work.

like image 67
Oleks Avatar answered Oct 23 '22 05:10

Oleks