Alex Rivera | Logout

Compare nullable types in Linq to Sql

Asked 2009-02-25T14:05:05.133
44

I have a Category entity which has a Nullable ParentId field. When the method below is executing and the categoryId is null, the result seems null however there are categories which has null ParentId value.

What is the problem in here, what am I missing?

public IEnumerable<ICategory> GetSubCategories(long? categoryId)
{
    var subCategories = this.Repository.Categories.Where(c => c.ParentId == categoryId)
        .ToList().Cast<ICategory>();

    return subCategories;
}

By the way, when I change the condition to (c.ParentId == null), result seems normal.

Edit
Report

2 Answers

4

You need to use operator Equals:

 var subCategories = this.Repository.Categories.Where(c => c.ParentId.Equals(categoryId))
        .ToList().Cast<ICategory>();

Equals fot nullable types returns true if:

  • The HasValue property is false, and the other parameter is null. That is, two null values are equal by definition.
  • The HasValue property is true, and the value returned by the Value property is equal to the other parameter.

and returns false if:

  • The HasValue property for the current Nullable structure is true, and the other parameter is null.
  • The HasValue property for the current Nullable structure is false, and the other parameter is not null.
  • The HasValue property for the current Nullable structure is true, and the value returned by the Value property is not equal to the other parameter.

More info here Nullable<.T>.Equals Method

answered 2012-06-14T13:42:41.667
1

What about something simpler like this?

public IEnumerable<ICategory> GetSubCategories(long? categoryId)
{
    var subCategories = this.Repository.Categories.Where(c => (!categoryId.HasValue && c.ParentId == null) || c.ParentId == categoryId)
        .ToList().Cast<ICategory>();

    return subCategories;
}
answered 2009-02-25T15:04:07.457

Your Answer