我无法使过滤器与MongoDB .NET Driver一起使用时,出现此错误:
Unsupported filter: Invoke(value(System.Func2 [Role,System.Boolean]), {document}{Model}).
尝试运行此代码时:
public virtual async Task<PartitionedModel<T>> GetByAsync(Func<T, bool> filter)
{
Expression<Func<PartitionedModel<T>, bool>> filt = (i) => filter(i.Model);
PartitionedModel<T> item = (await collection.FindAsync(filt)).FirstOrDefault();
return item;
}
和类 PartitionedModel 如下:
public class PartitionedModel<T> where T : IModel
{
public ObjectId Id { get; set; }
public PartitionOffset PartitionOffset { get; set; }
public T Model { get; set; }
}
从对集合进行直接处理 IModel 到使用 PartitionedModel (我的 IModel 的持有类)工作,我对代码进行了修改, GetByAsync 函数在我为 IModel
子类化之前可以正常工作除以下内容外,我几乎没有发现有关此问题的信息: Dynamic Linq Predicate throws "Unsupported Filter" error with C# MongoDB Driver
但是似乎我的MongoDB C#驱动程序版本不接受参数中的 Func <> 作为过滤器,我只能传递 Builder <> 或 Expression <> 作为查找功能的过滤器
有人可以启发我一些有关此错误的信息吗?
编辑:
我尝试通过将FindAsync(filt)
替换为FindAsync(_ => true)
来运行此代码,并且确实有效
此外,这是用于检索集合的代码
protected readonly IMongoCollection<PartitionedModel<T>> collection;
public GenericRepository(IMongoDatabase dbContext, string collectionName)
{
collection = dbContext.GetCollection<PartitionedModel<T>>(collectionName);
}
编辑2: 我使用以下方法使查询有效:
PartitionedModel<T> item = collection.AsQueryable().FirstOrDefault(filt);
但是我不确定使用非异步版本的含义是什么,任何人都可以告诉我这是错误的还是问题所在?
答案 0 :(得分:0)
似乎不支持基于委托的筛选器,如c#mongo驱动程序的当前实现。
该开关不包含ExpressionType.Invoke(基于委托的过滤器中的表达式类型)大小写。
答案 1 :(得分:0)
Mongo不适用于调用过滤器。您可以将该调用过滤器传递给LINQKit的表达式扩展器,并将其替换为Mongo驱动程序可以完全理解的谓词。