Linq to SQL检查null奇怪性

时间:2016-08-08 06:54:38

标签: c# linq

当我检查空值时,我有一个Linq to SQL查询(在我看来)非常奇怪。

如上一个Linq所示,DB中有一条记录,但为什么前两个查询没有显示记录?

//Check
(record.SomeID == null ? "Yes" : "No"); //This prints Yes

//LINQ
var q = (from t in mySQLTable
         where t.PKID == record.PKID && 
         t.SomeID == record.SomeID
         select t).FirstOrDefault();
 //This prints nothing.  I.e. no records found

var q2 = (from t in mySQLTable
          where t.PKID == record.PKID &&
          t.SomeID == (record.SomeID == null ? null : record.SomeID)
          select t).FirstOrDefault();
 //This also prints nothing.  I.e. no records found

 var q3 = (from t in mySQLTable
           where t.PKID == record.PKID &&
           t.SomeID == null
           select t).FirstOrDefault();
 //This prints 1 record

1 个答案:

答案 0 :(得分:1)

您可以使用以下查询克服此问题:

bool isNull = record.SomeID == null;

var q = (from t in mySQLTable
         where t.PKID == record.PKID 
         && ( (isNull && t.SomeID == null)
             ||
              (!isNull && t.SomeID == record.SomeID)
            )
         select t).FirstOrDefault();