创建动态Where子句作为Linq表达式 [英] Creating a Dynamic Where Clause as a Linq Expression

查看:68
本文介绍了创建动态Where子句作为Linq表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将条件动态地附加到单个表达式对象中,然后将该表达式对象传递给将使用该条件的方法.但是,我不断收到目前无法使用班级名称"的信息.

I am trying to dynamically append where conditions into a single expression-object, then pass that expression-object into a method that will use it. However, I keep getting "class name is not available at this point".

提前谢谢!

更新:
我终于能够创建一个 此处的工作示例 .

UPDATE:
I finally was able to create a working example here.

代码如下:

    var view = new vw_QuickFindResult();

   // This wont compile
    Expression<Func<vw_QuickFindResult, bool>> where = Expression<Func<vw_QuickFindResult, bool>>(view, true);

    // Build LIKE Statement
    var searches = new List<String>(searchText.Split(' '));
    searches.ForEach(productName =>
    {
        productName.Replace('"', '%');
        productName.Replace('*', '%');
        where = x => SqlMethods.Like(view.DocumentName, productName);
    });

    return DocumentCollectionService.ListQuickFind(where);

推荐答案

这是一个问题:

where = x => SqlMethods.Like(view.DocumentName, productName);

您在这里忽略了x,而是使用了刚刚初始化的view.我怀疑你想要

You're ignoring the x here, instead using view which you've just initialized. I suspect you want:

where = x => SqlMethods.Like(x.DocumentName, productName);

但是每次都会替换 现有的where表达式.我认为您应该使用Joe Albhari的 PredicateBuilder .我也避免亲自使用ForEach:

However that will replace the existing where expression each time. I think you should be using PredicateBuilder by Joe Albhari. I'd avoid using ForEach too, personally:

var where = PredicateBuilder.False<vw_QuickFindResult>();

// Build LIKE Statement
foreach (string productName in searchText.Split(' '))
{
    string like = productName.Replace('"', '%');
                             .Replace('*', '%');
    where = where.Or(x => SqlMethods.Like(view.DocumentName, like));
}

return DocumentCollectionService.ListQuickFind(where);

(我正在猜测您想要的功能;您可能需要PredicateBuilder.TrueAnd扩展方法.)

(I'm guessing at the functionality you want; you may want PredicateBuilder.True and the And extension method instead.)

这篇关于创建动态Where子句作为Linq表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆