EF Core 3 x.Contains() 在表达式中,其中 x 是 ICollection [英] EF Core 3 x.Contains() in expression where x is ICollection
问题描述
我有以下数据层设置:
public class Repository : IRepository {
private readonly MyDbContext _dbContext;
public List<Meter> Search(Expression<Func<Meter,bool>> criteria)
IQueryable<Meter> results = _dbContext.Meters;
return results.Where(criteria).ToList();
}
}
}
... from a client class:
IRepository _repository;
public void ClientMethod () {
ICollection<int> ids = new List<int>() {1, 2, 3);
var results = _repository.Search(c=> ids.Contains(c.Id)); // This throws exception
}
这导致异常:
表达式 Where(source: DbSet, predicate: (m) =>(未处理的参数: __ids_0).Contains(m.Id))' 不能翻译.要么以可翻译的形式重写查询,或通过插入调用显式切换到客户端评估AsEnumerable()、AsAsyncEnumerable()、ToList() 或 ToListAsync()
expression Where(source: DbSet, predicate: (m) => (Unhandled parameter: __ids_0).Contains(m.Id))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
但是如果我将集合引用更改为 IEnumerable 或 List,它会起作用:
But if I change the collection reference to IEnumerable or List, it works:
public void ClientMethod () {
// This works
List<int> ids = new List<int>() {1, 2, 3);
var results = _repository.Search(c=> ids.Contains(c.Id));
// This works
IEnumerable<int> ids = new List<int>() {1, 2, 3);
var results = _repository.Search(c=> ids.Contains(c.Id));
}
为什么它不适用于 ICollection,但适用于 IEnumerable 和 List?我的许多客户端方法都将 ICollection 作为参数.
Why is it not working for ICollection, but it does for IEnumerable and List? Many of my client methods take an ICollection as a parameter.
我使用的是 EF Core 3.0,但我相信我在 2.1 中遇到了同样的问题,它只是在客户端上评估时没有抛出.
I'm using EF Core 3.0 but I believe I had the same problem in 2.1, it just didn't throw as it evaluated it on the client instead.
推荐答案
这是 3.1 中修复的已知错误.由于查询管道重写后的所有回归,3.0 几乎无法使用.
This is a known bug fixed in 3.1. 3.0 is almost unusable due to all regressions after the query pipeline rewrite.
我建议在 github 上关注 ef 核心的问题跟踪器.
I recommend following the issue tracker on github for ef core.
这篇关于EF Core 3 x.Contains() 在表达式中,其中 x 是 ICollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!