简体   繁体   English

Linq表达式查询中的Nullable Int比较

[英]Nullable Int comparison in Linq Expression Query

I have a query that is returning 0 results when the database has valid entries. 当数据库具有有效条目时,我有一个查询返回0个结果。 I think this is down to a nullable foreign key on the comparison. 我认为这取决于比较中可为空的外键。

I have; 我有;

return context.Where<Job>(
       x =>
       x.StatusId != completeStatus.Id &&
       x.StatusId != cancelledStatus.Id).ToList();

where StatusId is; StatusId在哪里;

[ForeignKey("Status")]
public int? StatusId { get; set; }

I want to include all jobs where the StatusId is either null or not the value of the 2 Ids (arbitary integers). 我想包括所有StatusId为null或不是2 Ids(任意整数)值的作业。

How can I correct the above statement to return results please? 我如何更正以上声明以返回结果?

This should do it (if it is LINQ to Entities because it handles comparison to nullables in a somewhat SQL like way) 应该这样做(如果它是LINQ to Entities,因为它以某种类似于SQL的方式处理与nullable的比较)

!x.StatusId.HasValue
|| (x.StatusId!= completeStatus.Id
  && x.StatusId != cancelledStatus.Id) 

With other LINQ providers you may need to use x.StatusId.Value in the value comparisons. 对于其他LINQ提供程序,您可能需要在值比较中使用x.StatusId.Value

You can add the OR for the StatusId is null 您可以为StatusId为null添加OR

return context.Where<Job>(
   x =>
   (x.StatusId != completeStatus.Id &&
   x.StatusId != cancelledStatus.Id) ||
   x.StatusId == null).ToList();

From your description, I think you want something like this: 根据您的描述,我认为您需要这样的东西:

return context.Where<Job>(
       x =>
       !x.HasValue ||
       (x.StatusId.Value != completeStatus.Id &&
       x.StatusId.Value != cancelledStatus.Id)).ToList();

It's important to remember that an int? 重要的是要记住一个int? isn't a base type and does not in any way inherit from int / Int32 . 不是基本类型,也不从int / Int32继承。 It's just syntactic sugar for Nullable<int> . 它只是Nullable<int>语法糖。 It's an object with a Value property that may be null. 这是一个具有Value属性的object ,该属性可能为null。 This is true of any Nullable<T> . 任何Nullable<T>都是如此。

It's also important to implement parentheses to separate your comparisons to prevent unpredictable results and make code maintenance easier. 实施括号以分隔比较也很重要,以防止出现不可预测的结果并使代码维护更容易。 Here, it makes it clear that we want all results that are either without a value for x , or those whose value exists and both doesn't match completeStatus.Id and cancelledStatus.Id . 在这里,可以很清楚地看到我们想要的所有结果要么没有x的值,要么是其值存在且都与completeStatus.IdcancelledStatus.Id不匹配的结果。

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

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