簡體   English   中英

在多列中搜索詞

[英]Search a term in multiple columns

我想創建一個擴展以在多個列中搜索詞。 術語用空格隔開,每個術語必須出現在至少一個給定的列中。

這是我到目前為止所做的:

public static IQueryable<TSource> SearchIn<TSource>(this IQueryable<TSource> query, 
    string searchText, 
    Expression<Func<TSource, string>> expression, 
    params Expression<Func<TSource, string>>[] expressions)
{
    if (string.IsNullOrWhiteSpace(searchText))
    {
        return query;
    }

    // Concat expressions
    expressions = new[] { expression }.Concat(expressions).ToArray();

    // Format search text
    var formattedSearchText = searchText.FormatForSearch();
    var searchParts = formattedSearchText.Replace('\'', ' ').Split(' ');

    // Initialize expression
    var pe = Expression.Parameter(typeof(TSource), "entity");
    var predicateBody = default(Expression);

    // Search in each expressions, put OR in between
    foreach (var expr in expressions)
    {
        var exprBody = default(Expression);

        // Search for each words, put AND in between
        foreach (var searchPart in searchParts)
        {
            // Create property or field expression
            var left = Expression.PropertyOrField(pe, ((MemberExpression)expr.Body).Member.Name);

            // Create the constant expression with current word
            var search = Expression.Constant(searchPart, typeof(string));

            // Create the contains function
            var contains = Expression.Call(left, typeof(string).GetMethod(nameof(string.Contains), new Type[] { typeof(string) }), search);

            // Check if there already a predicate body
            if (exprBody == null)
            {
                exprBody = contains;
            }
            else
            {
                exprBody = Expression.And(exprBody, contains);
            }
        }

        if (predicateBody == null)
        {
            predicateBody = exprBody;
        }
        else
        {
            predicateBody = Expression.OrElse(predicateBody, exprBody);
        }
    }

    // Build the where method expression
    var whereCallExpression = Expression.Call(
        typeof(Queryable),
        nameof(Queryable.Where),
        new Type[] { query.ElementType },
        query.Expression,
        Expression.Lambda<Func<TSource, bool>>(predicateBody, new ParameterExpression[] { pe }));

    // Apply the condition to the query and return it
    return query.Provider.CreateQuery<TSource>(whereCallExpression);
}

只要給定的表達式很簡單,它就可以很好地工作:

// It works well
query.SearchIn("foo", x => x.Column1, x => x.Column2);

但是在嘗試瀏覽導航屬性時它不起作用:

// Not working
query.SearchIn("foo", x => x.Nav1.Column1);

這給了我一個例外。

“ Column1”不是“ Nav1”類型的成員。

我知道問題所在,但找不到通過Nav1傳遞的解決方案。

我需要這方面的幫助。

無需解析lambda表達式主體,只需使用給定參數調用它即可:

var left = Expression.Invoke(expr, pe);

但是,它僅在EF Core中有效。

在EF6中,您將需要獲取每個嵌套成員的屬性或字段,如下所示:

var left = expr.Body.ToString()
    .Split('.')
    .Skip(1) //skip the original parameter name
    .Aggregate((Expression)pe, (a, c) => Expression.PropertyOrField(a, c));

它僅適用於簡單的lambda,例如:

x => x.Prop1.Nav1

如果這還不夠的話,您將需要使用ExpressionVisitor更高級的解析算法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM