Answered by:
Linq result fails when checking for null value for column.

Question
-
User-2054057000 posted
Why this Linq query fails?
string blogCategoryId=null;
var r1 = context.Blog.Where(x => (blogCategoryId != null && x.CategoryId == blogCategoryId)).ToList();I want this query should return all blogs without where condition since blogCategoryId is null.
But this query return 0 records stating the where condition x.CategoryId == blogCategoryId has been applied?
Why it is so?
Tuesday, January 15, 2019 12:37 PM
Answers
-
User-821857111 posted
var r1 = context.Blog.Where(x => (blogCategoryId == null || x.CategoryId == blogCategoryId)).ToList();
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, January 15, 2019 1:21 PM
All replies
-
User-821857111 posted
string blogCategoryId=null; var r1 = context.Blog.Where(x => (blogCategoryId != null && x.CategoryId == blogCategoryId)).ToList();
Tuesday, January 15, 2019 12:42 PM -
User-2054057000 posted
Mikesdotnetting
yogyogi
string blogCategoryId=null; var r1 = context.Blog.Where(x => (blogCategoryId != null && x.CategoryId == blogCategoryId)).ToList();
The condition "blogCategory != null" will always be false. Therefore no records will ever be returned.
Actually I want my condition to work this way.
- If blogCategoryId is null then apply no check in where and return context.blog.
- if blogCategoryId is not null then apply check in where and return context.blog(x=>x. CategoryId==blogCategoryId);
How to do it?
Tuesday, January 15, 2019 12:55 PM -
User-821857111 posted
var r1 = context.Blog.Where(x => (blogCategoryId == null || x.CategoryId == blogCategoryId)).ToList();
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, January 15, 2019 1:21 PM -
User-2054057000 posted
Thanks, knew the problem which I was doing. Thank you!
Tuesday, January 15, 2019 1:39 PM