无法比较EF查询中的元素异常

Nat*_*oop 9 c# entity-framework-4.1

我基本上:

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);
}
Run Code Online (Sandbox Code Playgroud)

目标是仅获取具有传递的ID的项目或返回所有项目.(其他标准为清晰起见)

当我返回时myList,我得到一个异常,我做了一些调试,并在执行时发生.ToList()

无法比较'System.Collections.Generic.List`1'类型的元素.
仅支持基本类型(例如Int32,String和Guid)和实体类型.

Nat*_*oop 22

问题是因为myIds为null.

我需要:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 更具体地说,这是因为你在'where'子句中进行了空检查. (17认同)