【问题标题】:Cannot compare elements exception in EF query无法比较 EF 查询中的元素异常
【发布时间】:2015-06-16 09:32:54
【问题描述】:

我基本上有:

public ActionResult MyAction(List<int> myIds)
{
    var myList = from entry in db.Entries
             where (myIds == null || myIds.Contains(entry.Id))
                 select entry;
    return View(myList);
}

目标是仅获取具有传递 Id 的项目或返回所有项目。 (为清楚起见,剪掉了其他标准)

当我返回 myList 时出现异常,我已经进行了一些调试,它在执行 .ToList() 时发生

无法比较“System.Collections.Generic.List`1”类型的元素。
只有原始类型(例如 Int32、String 和 Guid)和实体 支持类型。

【问题讨论】:

标签: c# entity-framework-4.1


【解决方案1】:

问题是因为 myIds 为空。

我需要:

public ActionResult MyAction(List<int> myIds)
{
    if(myIds == null)
    {
        myIds = new List<int>();    
    }
    bool ignoreIds = !myIds.Any();

    var myList = from entry in db.Entries
                 where (ignoreIds || myIds.Contains(entry.Id))
                 select entry;
    return View(myList);
}

【讨论】:

  • 更具体地说,这是因为您在“where”子句中进行了空检查。
  • 哦!谢谢@htxryan。我几乎错过了您的评论,但它节省了我对更多答案的搜索
猜你喜欢
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2022-12-19
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
相关资源
最近更新 更多