如何使用Mongodb C#驱动程序进行谓词搜索

3
如何在强大的MongoDB C#驱动程序中使用以下方法?
public IList<TEntity>SearchFor(Expression<Func<TEntity, bool>> predicate)
            {
                return collection
                    .AsQueryable<TEntity>()
                        .Where(predicate.Compile())
                            .ToList();
            }

例子将非常理想!
1个回答

3

只需删除 Compile,因为它创建了一个 delegate,驱动程序无法将其转换为Mongo查询:

public IList<TEntity>SearchFor(Expression<Func<TEntity, bool>> predicate)
{
    return collection
        .AsQueryable<TEntity>()
            .Where(predicate)
                .ToList();
}

然而,这意味着谓词表达式必须能够被MongoDB驱动程序翻译。


好的。你可以给我一个如何使用它的例子吗? - InCode
@ENC0D3D 这取决于你的TEntity是什么,但是这里是:SearchFor(hamster => hamster.Name == "Bar") - i3arnon
我尝试过了,但它返回0条记录。无论是否编译... IList<tickets> lstTickets = _ticketRepository.SearchFor(x => x.description == search); - InCode
为什么不会呢?你有一只名叫巴尔的仓鼠吗? - i3arnon
@ENC0D3D 我不太明白你想要什么。 - i3arnon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接