maztt
maztt

Reputation: 12294

linq to sql checking for null

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

Upvotes: 7

Views: 34880

Answers (4)

Escarcha
Escarcha

Reputation: 447

I have this query working in this scenario

YourContext db = new YourContext();
List<entity> list =  (from n in db.YourEntity
                     where n.FieldToCheck.Equals(null)
                     select n).ToList();

Hope it helps.

Upvotes: 0

Johannes Rudolph
Johannes Rudolph

Reputation: 35741

This question is actually not easily answered given the lack of context you provide, though usually _db.Categories.Where(m => m.int_ParentId.Equals(null)); does what you want.

There are a couple of discrepancies between the CTS (.NETs type system) and the SQL type system.

See SQL-CLR Type Mismatches - MSDN and Null Semantics - MSDN for the full reference.

Especially null will cause you headaches if you don't take enough care, since it has two completely different meanings in the respective typesystems. NULL in SQL means, "value absent, will match any comparison", whereas null in .NET means "no object, comparing against null will always yield false".

Upvotes: 6

Oleks
Oleks

Reputation: 32323

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.

Upvotes: 27

Kelsey
Kelsey

Reputation: 47726

I think you want to use the object's Equals method:

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

Upvotes: 2

Related Questions