c# - EF6 Linq - 如何创建相当于 "where(List == null || List.Contains(obj))"的过滤器表达式?

标签 c# linq entity-framework-6

我正在尝试执行以下操作(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/

相关文章:

c# - 如何防止 Entity Framework 6在配置文件中创建绑定(bind)重定向

c# - System.ObjectDisposeException : 'Cannot access a disposed object.Object name: ' OracleConnection'. '

c# - 如何使用 Pinvoke 返回字符串数组

c# - System.Timers.Timer 几毫秒后第二次触发

c# - 使用 DataTriggers 在运行时更改 DataTemplate

c# - Linq 选择两个列表中都存在的项目

c# - 使用 Linq 列出的数据集

c# - 如何计算积分?

c# - Entity Framework 使用 newsequentialid() 作为 Guid Key

c# - 如何分析二进制序列化流的内容?