Skip to main content
 首页 » 编程设计

c#之获取 IQueryableT>,其中 T 的任何字段包含给定字符串

2024年02月13日23落叶无声

我使用的 EF5 有一个由字符串、日期、可为 null 的日期和整数组成的大型 20 属性实体。是否可以使用 Linq 对每个字段进行包含。

我不想为每个字段都构建一个 linq 语句

results = list.Where(house => house.Date1.ToString().Contains(search)|| 
                              house.Address1.Contains(search)|| 
                              house.Address2.Contains(search)|| 
                              house.Address3.Contains(search)|| 
                              .........................) 

我想我想将所有属性转换为字符串(必要时),然后对每个属性进行包含?理想情况下,这将发生在数据库级别。

我想我不能连接它们,因为如果两个字段的结尾和开头创建了搜索文本,它可能会导致错误匹配?有什么想法吗?

更新

我目前是这个 LINQ string[] against multiple fields 的第二个答案使用 LinqKit AsExpandable 和 EF 转换函数到基于类型的字符串。但是我似乎无法找到将 DateTime 转换为字符串的 SqlFunction

请您参考如下方法:

所以这里的一般想法是使用 PredicateBuilder 将一堆表达式组合在一起,每个表达式代表对给定属性的 Contains 检查。您可以使用反射来查找给定类型的所有属性来为其创建表达式。

public static Expression<Func<T, bool>> SearchAllFields<T>(string searchText) 
{ 
    var t = Expression.Parameter(typeof(T)); 
    Expression body = Expression.Constant(false); 
 
    var containsMethod = typeof(string).GetMethod("Contains" 
        , new[] { typeof(string) }); 
    var toStringMethod = typeof(object).GetMethod("ToString"); 
 
    var stringProperties = typeof(T).GetProperties() 
        .Where(property => property.PropertyType == typeof(string)); 
 
    foreach (var property in stringProperties) 
    { 
        var stringValue = Expression.Call(Expression.Property(t, property.Name), 
            toStringMethod); 
        var nextExpression = Expression.Call(stringValue, 
            containsMethod, 
            Expression.Constant(searchText)); 
 
        body = Expression.OrElse(body, nextExpression); 
    } 
 
    return Expression.Lambda<Func<T, bool>>(body, t); 
}