动态构建Linq查询

动态构建Linq查询,linq,expression-trees,Linq,Expression Trees,我正在编写实现关键字样式搜索的LINQ查询。换句话说,返回标题,说明,Id包含以下内容的行的查询 如下 public static IQueryable<EmployeeObject> QueryableSQL() { IQueryable<EmployeeObject> queryable = EmployeeRepository.GetAllEmployee(); } public static IList<E

我正在编写实现关键字样式搜索的LINQ查询。换句话说,返回
标题
说明
Id
包含以下内容的行的查询

如下

    public static IQueryable<EmployeeObject> QueryableSQL()
    {
        IQueryable<EmployeeObject> queryable = EmployeeRepository.GetAllEmployee(); 
    }

    public static IList<EmployeeObject> QLike(string txt)
    {
       IList<employeeObject> _emps = QueryableSQL().Where(x => x.Title == txt).ToList();
       return _emps;
    }
publicstaticiqueryable QueryableSQL()
{
IQueryable queryable=EmployeeRepository.GetAllEmployee();
}
公共静态IList QLike(字符串txt)
{
IList_emps=QueryableSQL().Where(x=>x.Title==txt.ToList();
返回emps;
}
到目前为止,一切顺利。但这只处理您希望在我的案例中匹配的案例
Title


相反,假设我想根据“Description
Id
进行搜索,我是否应该为Description创建一个新方法?或者有没有一种方法可以创建一个
树表达式`

你看过了吗?也就是说,当然,如果此文本可能是用户提供的而不是编译的。

听起来您希望通过动态方式与正在进行比较的属性进行比较,您可以使用反射来执行此操作:

public static IQueryable<EmployeeObject> QueryableSQL()
{
    IQueryable<MediaObject> queryable = EmployeeRepository.GetAllEmployee(); 
}

public static IList<EmployeeObject> QLike(Expression<Func<EmployeeObject, bool>> func)
{
   return QueryableSQL().Where(func).ToList();
}
public static IList<EmployeeObject> QLike(string propName, string txt)
{
   PropertyInfo filterProp = typeof(EmployeeObject).GetProperty(propName);
   IList<employeeObject> _emps = QueryableSQL().Where(x => filterProp.GetValue(x, null).ToString() == txt).ToList();
   return _emps;
}
公共静态IList QLike(字符串propName,字符串txt)
{
PropertyInfo filterProp=typeof(EmployeeObject).GetProperty(propName);
IList_emps=QueryableSQL().Where(x=>filterProp.GetValue(x,null).ToString()==txt.ToList();
返回emps;
}
然而,这种方法的缺点是,最终将从数据库加载所有对象,然后在代码中过滤它们


如果您遵循@gleng shows的方法,那么Ling to SQL将能够在生成的SQL语句中进行过滤。在这种情况下,您确实需要预先对谓词进行编码,并根据要调用的属性调用相应的谓词。

您可以传入Func并在
中使用它,而不是传入字符串文本。
请给我举一个示例。这将适用于您在
EmployeeObject
中引入的任何新字段。在发布我的问题之前,我已经看到了这一点,我不确定这是否适合我的情况。理想情况下,您应该接受
表达式而不是
函数。这将使LINQ提供程序能够分析谓词并将其作为原始SQL查询的一部分。如果未过滤的结果集很大,这会产生巨大的差异。这可能是将一百万条记录读入内存或读取一条记录之间的区别。这正是我想要的,非常简洁clean@gleng:布尔表示什么
public static IList<EmployeeObject> QLike(string propName, string txt)
{
   PropertyInfo filterProp = typeof(EmployeeObject).GetProperty(propName);
   IList<employeeObject> _emps = QueryableSQL().Where(x => filterProp.GetValue(x, null).ToString() == txt).ToList();
   return _emps;
}