Linq query works with null but not int? in where clause

后端 未结 2 590
甜味超标
甜味超标 2021-01-12 13:48

I have a linq query function like (simplified):

public IList ListDocuments(int? parentID)
{
    return (
        from doc in dbContext.Docume         


        
相关标签:
2条回答
  • 2021-01-12 13:57

    You can use also something like ...

    from doc in dbContext.Documents
    where doc.IsParentIDNull()
    select doc
    

    It worked for me! hope it work for you!

    0 讨论(0)
  • 2021-01-12 14:14

    Literal null values are handled differently than parameters which could be null. When you explicitly test against null, the generated SQL will use the IS NULL operator, but when you're using a parameter it will use the standard = operator, meaning that no row will match because in SQL null isn't equal to anything. This is one of the more annoying .NET/SQL semantic mismatches in LINQ to SQL. To work around it, you can use a clause like:

    where doc.ParentID == parentID || (doc.ParentID == null && parentID == null)
    
    0 讨论(0)
提交回复
热议问题