简体   繁体   English

可空对象必须在Linq where子句中具有值

[英]Nullable object must have a value in Linq where clause

Why would a nullable int give this error using linq? 为什么可为空的int使用linq会给出此错误?

public void test(int? variableId)
{
     var date = _dbContext.Set<MyEvent>()
              .Where(x => x.Calendar.id == (variableId.HasValue ? variableId   : x.Calendar.id))
              .ToList();
}
  • variableId.HasValue is false variableId.HasValue为false
  • variableId is null variableId为null

You should write it as (variableId.HasValue ? variableId. Value : x.Calendar.id) 你应该把它写为(variableId.HasValue variableId :?x.Calendar.id)

Assuming variableId is null, then you have a very funny expression .Where(x => x.Calendar.id == x.Calendar.id) that means - all records. 假设variableId为null,那么您将得到一个非常有趣的表达式。其中(x => x.Calendar.id == x.Calendar.id)意味着-所有记录。 The problem with your code is that having your original where expression most likely cause client side filtering but not sql side filtering. 您的代码的问题在于,使用原始的where表达式很可能会导致客户端过滤,而不是sql过滤。 It is better to rewrite it like: 最好像这样重写它:

var date = variableId.HasValue
      ?_dbContext.Set<MyEvent>().Where(x => x.Calendar.id == variableId.Value))
      :_dbContext.Set<MyEvent>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM