我正在尝试执行以下操作(SelectedIdCollection 是 List 并且 cb.Id 是 int)-
db.Items.Where(cb => (SelectedIdCollection == null || SelectedIdCollection.Contains(cb.Id)))
基本上,如果 SelectedIdCollection
为 null 则返回所有内容,如果它不为 null 则按它进行过滤。
但它抛出以下错误 -
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code. Cannot compare elements of type 'System.Collections.Generic.IList`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported.
这个where条件还有其他写法吗?
最佳答案
自 SelectedIdCollection
是从表达式外部捕获的变量,您可以将其处理为 null
在进行表达式之前,然后将其视为非空:
var getEverything = SelectedIdCollection==null;
var targetCollection = SelectedIdCollection ?? new int[0];
var res = db.Items.Where(cb => getEverything || targetCollection.Contains(cb.Id));
现在targetCollection
保证是非 null
, 和 getEverything
标志涵盖了需要从数据库中选择所有内容的条件。
关于c# - EF6 Linq - 如何创建相当于 "where(List == null || List.Contains(obj))"的过滤器表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41383786/