Linq to sql check for zero

my database field int_ParentId consists of a Null value. how would I check it for null in this linq request. he does not work

return _db.Categories.Where(m => m.int_ParentId==null); 
+7
source share
4 answers

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

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

and

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

must work.

+25
source

This question is actually not easy to answer, given the lack of context that you provide, although usually _db.Categories.Where(m => m.int_ParentId.Equals(null)); does what you want.

There are several inconsistencies between the CTS (.NET type system) and the SQL type system.

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

In particular, null will lead to headaches if you do not take sufficient care, since it has two completely different meanings in the corresponding type systems. NULL in SQL means "no value will match any comparison," while NULL in .NET means "no objects comparing with zero will always give false."

+5
source

I think you want to use the Equals method:

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

This request works for me in this scenario

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

Hope this helps.

0
source

All Articles