MongoDb c#查询,where子句

本文关键字:where 子句 查询 MongoDb | 更新日期: 2023-09-27 18:08:22

我正在使用MongoDb,并且正在使用PredicateBuilder类在c#中动态创建where子句。但是异常生成为:

[系统。{"不支持where子句:."},

和动态生成的where子句

{c => (True AndAlso Invoke(c => (c.ID == value(ASP.search_aspx).txtid.Text), c))} , 
查询:使用

var result = collection.AsQueryable<USER>()
                      .Where(where_clause)
                      .Select(c => new { c.ID, c.COMPANYNAME, c.EMAIL 
                       }).Take(100).ToList();

收集的实例是MongoCollection

创建where_clause代码:

var where_clause = PredicateBuilder.True<GLUSR_USR>();
//object result=0;
if ((txtGlid.Text).Trim() != "")
{
    where_clause = where_clause.And(c => c.GLUSR_USR_ID == txtGlid.Text);
}
if ((txtEmailid.Text).Trim() != "")
{
    where_clause = where_clause.And(c => c.GLUSR_USR_EMAIL == txtEmailid.Text);
}
if ((txtPhone.Text).Trim() != "")
{
    where_clause = where_clause.And(c => c.GLUSR_USR_PH_NUMBER == txtPhone.Text);
}
if ((txtMobile.Text).Trim() != "")
{
    where_clause = where_clause.And(c => c.GLUSR_USR_PH_MOBILE == txtMobile.Text);
}

MongoDb c#查询,where子句

尝试使用AsExpandable():

var result = collection.AsQueryable<USER>()
                       .AsExpandable()
                       .Where(where_clause)
                       .Select(c => new { c.ID, c.COMPANYNAME, c.EMAIL 
                       }).Take(100).ToList();

AsExpandable()可以在LinqKit中找到

由于Invoke,看起来在闭包中捕获了对(ASP.search_aspx).txtid.Text的引用,而不是此时计算值。我可以要求您在局部显式地评估文本框的值,以防止表达式解析器弄乱的任何机会:

if (txtGlid.Text.Trim() != "")
{
    string s = txtGlid.Text;
    where_clause = where_clause.And(c => c.GLUSR_USR_ID == s);
}
它可能意味着你添加了' where c.ID == txtid。Text '作为谓词,而不是' where c.ID == txtid.Text() '。传入字符串值应该生成更简单的谓词' (True AndAlso c.ID == "someLiteralValue") ',希望可以由' Linq '提供程序解析。