EF:如何最小化搜索代码

时间:2018-02-08 12:49:41

标签: entity-framework

我正在使用4个字段,但我可能需要搜索100个字段。所以提到100个字段名称在哪里非常麻烦。

请在针对所有字段或少数特定字段搜索值时建议最佳方法。

    if (!String.IsNullOrEmpty(SearchText))
    {
        customer = customer.Where(s => s.CompanyName.ToUpper().Contains(SearchText.ToUpper())
        || s.ContactName.ToUpper().Contains(SearchText.ToUpper())
        || s.ContactTitle.ToUpper().Contains(SearchText.ToUpper())
        || s.Address.ToUpper().Contains(SearchText.ToUpper()));
    }

1 个答案:

答案 0 :(得分:0)

您可以动态创建predicate Expression

if(!String.IsNullOrEmpty(SearchText))
{
    Expression orExpr = null;
    var arg = Expression.Parameter(typeof(Customer), "x");

    var strType = typeof(string);
    var ToUpperMeth = strType.GetMethods().Where(x => x.Name == nameof(string.ToUpper) 
                                          && x.GetParameters().Count() == 0).Single();
    var ContainsMeth = strType.GetMethods().Where(x => x.Name == nameof(string.Contains) 
                                          && x.GetParameters().Count() == 1).Single();

    var exprVal = Expression.Constant(SearchText);
    var toUpExprVal = Expression.Call(exprVal, ToUpperMeth);

    foreach (var prop in typeof(Customer)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Where(x => x.PropertyType == strType))
    {
        var exprProp = Expression.Property(arg, prop.Name);
        var toUpExpr = Expression.Call(exprProp, ToUpperMeth);
        var contExpr = Expression.Call(toUpExpr, ContainsMeth, toUpExprVal);

        orExpr = orExpr == null ? (Expression)contExpr : Expression.Or(orExpr, contExpr);
    }
    var predicate = Expression.Lambda<Func<Customer, bool>>(orExpr, arg);

    customer = customer.Where(predicate);
}