【问题标题】:C# Linq use Where with IsNull() Operator '&&' cannot be applied to operands of type 'bool' and 'int?'C# Linq 使用 Where 和 IsNull() 运算符“&&”不能应用于“布尔”和“整数”类型的操作数?
【发布时间】:2014-07-31 23:30:51
【问题描述】:

我正在将旧的经典 asp 站点转换为 .NET MVC 5、Entity Framework 6。

我被困在一个我无法弄清楚的 linq 查询上。 这是我原来的 SQL 查询:

@"SELECT DISTINCT AC.id, AC.name, ISNULL(AC.[order], 999) 
        FROM tbl12AuditCategories AC 
        INNER JOIN tbl12AuditQuestions AQ ON AC.id = AQ.new_categoryId 
        WHERE AQ.include = 1 AND AC.include = 1 AND ISNULL(AC.AuditQuestionGroupId, '0') = ? 
        ORDER BY ISNULL(AC.[order], 999), AC.name";

我会将一个值传递给 ISNULL(AC.AuditQuestionGroupId, '0') = ?。现在有了 Linq,我可以轻松地传递值。

 PracticeConductViewModel pcvm = new PracticeConductViewModel();
            pcvm.Categories = (from x in _repository.GetAll<ReviewCategory>()
                               join y in _repository.GetAll<ReviewQuestion>()
                                on x.id equals y.CategoryId
                               orderby x.order == null ? 999 : x.order, x.name
                              where x.include == true && y.include == true && (x.AuditQuestionGroupId != null ? this.LoggedInEntity.AuditQuestionGroupId : 0)
                              select x).ToList();

我的问题是这一行: 其中 x.include == true && y.include == true && (x.AuditQuestionGroupId != null ? this.LoggedInEntity.AuditQuestionGroupId : 0)

我得到错误:

Operator '&&' cannot be applied to operands of type 'bool' and 'int?'

我明白它在告诉我什么,但我不知道如何正确获取从 SQL 转换而来的 ISNULL(..) 函数。

【问题讨论】:

  • 您缺少 SQL 查询中的比较。
  • 在那里:ISNULL(AC.AuditQuestionGroupId, '0') = ?
  • 是的,这是在 SQL 查询中,但不在 LINQ 查询中,这就是您的问题的原因,正如@MikeParkhill 在他的回答中指出的那样。

标签: c# asp.net sql linq asp.net-mvc-5


【解决方案1】:

这 (x.AuditQuestionGroupId != null ? this.LoggedInEntity.AuditQuestionGroupId : 0) 解析为一个可空的 int,它显然不属于布尔条件的一部分。

你的意思是这样的:

where x.include == true && y.include == true
   && ((x.AuditQuestionGroupId != null ? x.AuditQuestionGroupId : 0) ==  this.LoggedInEntity.AuditQuestionGroupId)

【讨论】:

  • 一些广告:使用空合并运算符使您的查询更短(并且从 SQL 转换 ISNULL 非常有用):[...] &amp;&amp; ((x.AuditQuestionGroupId ?? 0) == this.LoggedInEntity.AuditQuestionGroupId)
猜你喜欢
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
相关资源
最近更新 更多