我正在尝试找到一个适用于下面查询的语句。 我可以使用相同的代码查询空值或整数值,但不能同时查询两者。
int? age = null;
Student student;
age = 12;
//works
student = entities.Students.Single(s => s.Age == age);
//does not work - crash
student = entities.Students.Single(s => s.Age.Equals(age));
age = null;
//works
student = entities.Students.Single(s => s.Age.Equals(age));
请注意第一个答案:
//crashes with error - sequence contains no elements
age = null;
student = entities.Students.Single(s => s.Age == age);
答案 0 :(得分:2)
不幸的是,这是well known and reported issue。解决方法是:
student = entities.Students.Single(s => age == null ? s.Age == null : s.Age == age);
答案 1 :(得分:0)
student = entities.Students.Single(s => s.Age == age);
那个应该满足你的要求,检查空值的相等性和值本身。