Linq IQueryable 通用过滤器

ine*_*e p 3 c# linq entity-framework c#-4.0

我正在为任何列/字段映射的查询中的 searchText 寻找通用过滤器

public static IQueryable<T> Filter<T>(this IQueryable<T> source, string searchTerm)
{
   var propNames = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(e=>e.PropertyType == typeof(String)).Select(x => x.Name).ToArray();


 //I am getting the property names but How can I create Expression for

 source.Where(Expression)
}
Run Code Online (Sandbox Code Playgroud)

在这里我给你一个示例场景

现在从我在 Asp.net MVC4 中的 HTML5 表中,我提供了一个搜索框来过滤输入文本的结果,它可以匹配以下任何列/菜单类属性值,我想在服务器端进行此搜索,如何我可以实施吗。

EF 模型类

 public partial class Menu
    {
        public int Id { get; set; }
        public string MenuText { get; set; }
        public string ActionName { get; set; }
        public string ControllerName { get; set; }
        public string Icon { get; set; }
        public string ToolTip { get; set; }
        public int RoleId { get; set; }

        public virtual Role Role { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

Dus*_*gen 5

您可以使用表达式:

private static Expression<Func<T, bool>> GetColumnEquality<T>(string property, string term)
{
    var obj = Expression.Parameter(typeof(T), "obj");        

    var objProperty = Expression.PropertyOrField(obj, property);
    var objEquality = Expression.Equal(objProperty, Expression.Constant(term));

    var lambda = Expression.Lambda<Func<T, bool>>(objEquality, obj);

    return lambda;
}

public static IQueryable<T> Filter<T>(IQueryable<T> source, string searchTerm)
{
    var propNames = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(e => e.PropertyType == typeof(string))
                             .Select(x => x.Name).ToList();

    var predicate = PredicateBuilder.False<T>();

    foreach(var name in propNames)
    {
        predicate = predicate.Or(GetColumnEquality<T>(name, searchTerm));
    }

    return source.Where(predicate);
}
Run Code Online (Sandbox Code Playgroud)

PredicateBuilder在 NutShell 中与 C# 中的名称相结合。这也是LinqKit的一部分。

例子:

public class Foo
{
    public string Bar { get; set; }
    public string Qux { get; set; }
}

Filter<Foo>(Enumerable.Empty<Foo>().AsQueryable(), "Hello");

// Expression Generated by Predicate Builder
// f => ((False OrElse Invoke(obj => (obj.Bar == "Hello"), f)) OrElse Invoke(obj => (obj.Qux == "Hello"), f))
Run Code Online (Sandbox Code Playgroud)