Creating a Dynamic Where Clause as a Linq Expressi

2019-08-07 18:27发布

问题:

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".

Thanks in advance!

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

The Code Look Like:

    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);

回答1:

This is one problem:

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

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);

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);

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