5

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;
    }
1
  • check if(ParenCategoryID isEqualTo:NULL) then do what you want. Commented May 5, 2012 at 9:32

2 Answers 2

8

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;
} 
Sign up to request clarification or add additional context in comments.

3 Comments

object.Equals will be translated to sql? if yes how query will look like?
@Reniuz Yes it will, it will be: WHERE [t0].[ParenCategoryId] IS NULL
@Reniuz yes, and it is optimized by Linq to Sql depending on the nullable variable's value: brentlamborn.com/post/…
0

You can try the following

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.