MongoDb 传递谓词参数

本文关键字:参数 谓词 MongoDb | 更新日期: 2023-09-27 18:37:17

in MongoDb 例如,我可以将谓词传递给可查询的实例

DataBase.GetCollection<BsonDocument>("entity")
    .AsQueryable<Entity>()
    .Where(item=>item.id ==5);

但现在我有这样的功能

IEnumerbale QueryData(Predicate<Entity> condition)
{
    this.DataBase.GetCollection<BsonDocument>("entity")
        .AsQueryable<Entity>()
        .Where(item=> condition(item));
}

但这不起作用,并告诉我:

不支持的 where 子句:。

这是设计出来的吗?有什么解决方法吗?我做错了什么吗?

MongoDb 传递谓词参数

你甚至没有传递表达式。你的条件对MongoDB来说是一个完全不透明的函数。

您需要传入一个Expression<Func<Entity,bool>>并像这样调用 where:

Where(condition)

Where 子句必须转换为发送到服务器的 MongoDB 查询。当您传入这样的任意谓词时,LINQ 层不知道要将其转换为什么。因此,不能支持这种类型的开放式 Where 子句。

将 Lambda 表达式作为参数传递以过滤来自 mongodb 集合的数据。您的数据过滤器功能可能是

public IEnumerable<BsonDocument> FindAllWithPredicate(Func<BsonDocument, bool> condition)
{
    return Collection.AsQueryable().Where(condition).ToArray();
}

谓词生成器.cs

public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>()
    {
        return f => true;
    }
    public static Expression<Func<T, bool>> False<T>()
    {
        return f => false;
    }
    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
            (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }
    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
            (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}   

通过谓词生成器生成 lambda 表达式

public static class PredicateBuilderStore
{
    public static Func<BsonDocument, bool> GetPredicateForBsonDocument(Entity entity)
    {
        var predicate = PredicateBuilder.True<BsonDocument>();            
        predicate = predicate.And(d => d.GetElement({key}).Value == CompareWithValue);
        return predicate.Compile();
    }   
}

如果只想查询所有项目,可以按以下方式查询:

return this.collection.Find(_=>true).ToArray();