Linq-to-SQL using int? with a null value
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)
开发者_如何学JAVA .ToList();
else
return _repository.GetMenus()
.Where(x => x.ParentId == menu.ParentId && x.WikiId == site.Id)
.ToList();
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.
精彩评论