0

I'm having some problems with a Linq-to-SQL query

Now if I run this request, everything run just fine and I get the right results back (2 rows).

return _repository.GetMenus()
                .Where(x => x.ParentId == null && x.WikiId == 1)
                .ToList();

But if I do the following, I just get an empty list.

var menu = new WikiMenu();
menu.ParentId = null;
return  _repository.GetMenus()
                   .Where(x => x.ParentId == menu.ParentId && x.WikiId == 1)
                   .ToList();

But if menu.ParentId is anything else then null it does work just fine.

This is the model WikiMenu

public class WikiMenu
{
    public int? Id { get; set; }
    public int WikiId { get; set; }
    public int PageId { get; set; }
    public string Title { get; set; }
    public int Order { get; set; }
    public int? ParentId { get; set; }
    public List<WikiMenu> SubMenu { get; set; }
}

How can I fix this?

So far have I done this little hack

if(menu.ParentId == null)
     return _repository.GetMenus()
                       .Where(x => x.ParentId == null && x.WikiId == site.Id)
                       .ToList();
else
     return _repository.GetMenus()
                       .Where(x => x.ParentId == menu.ParentId && x.WikiId == site.Id)
                       .ToList();

1 Answer 1

3

You can try to use the following code:

return _repository.GetMenus().  
    Where(x => object.Equals(x.ParentId, menu.ParentId) && x.WikiId == 1).ToList();

This code snippet will force Linq2SQL to generate something like WHERE [table0].[parentId] IS NULL rather than WHERE [table0].[parentId] == NULL.

Hope this helps.

Sign up to request clarification or add additional context in comments.

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.