LINQ to SQL - nullable types in where clause

前端 未结 3 441
情歌与酒
情歌与酒 2020-12-31 10:59

I have a table with a column that has null values... when I try to query for records where that column IS NULL:

THIS WORKS:



        var list = from         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 11:46

    One possibility - if mt.PARENT_KEY is of some other type (e.g. long?) then there will be conversions involved.

    It would help if you could show the types involved and the query generated in each case.

    EDIT: I think I have an idea...

    It could be because SQL and C# have different ideas of what equality means when it comes to null. Try this:

    where (mt.PARENT_KEY == id) || (mt.PARENT_KEY == null && id == null)
    

    If this is the case then it's a pretty ugly corner case, but I can understand why it's done that way... if the generated SQL is just using

    WHERE PARENT_KEY = @value
    

    then that won't work when value is null - it needs:

    WHERE (PARENT_KEY = @value) OR (PARENT_KEY IS NULL AND @value IS NULL)
    

    which is what the latter LINQ query should generate.


    Out of interest, why are you selecting with

    select new { mt.NAME }
    

    instead of just

    select mt.NAME
    

    ?) Why would you want a sequence of anonymous types instead of a sequence of strings (or whatever type NAME is?

提交回复
热议问题