【发布时间】:2009-05-31 06:12:17
【问题描述】:
我正在使用实体框架并开发了这个扩展方法:
public static IQueryable<TResult> Like<TResult>(this IQueryable<TResult> query, Expression<Func<TResult, string>> field, string value)
{
var expression = Expression.Lambda<Func<TResult, bool>>(
Expression.Call(field.Body, typeof(string).GetMethod("Contains"),
Expression.Constant(value)), field.Parameters);
return query.Where(expression);
}
如果我这样使用,这段代码可以正常工作:
var result = from e in context.es.Like(r => r.Field, "xxx")
select e
现在我需要以编程方式调用这个扩展方法:
public static IQueryable<TSource> SearchInText<TSource>(this IQueryable<TSource> source, string textToFind)
{
// Collect fields
PropertyInfo[] propertiesInfo = source.ElementType.GetProperties();
List<string> fields = new List<string>();
foreach (PropertyInfo propertyInfo in propertiesInfo)
{
if (
(propertyInfo.PropertyType == typeof(string)) ||
(propertyInfo.PropertyType == typeof(int)) ||
(propertyInfo.PropertyType == typeof(long)) ||
(propertyInfo.PropertyType == typeof(byte)) ||
(propertyInfo.PropertyType == typeof(short))
)
{
fields.Add(propertyInfo.Name);
}
}
ParameterExpression parameter = Expression.Parameter(typeof(TSource), source.ElementType.Name);
Expression expression = Expression.Lambda(Expression.Property(parameter, typeof(TSource).GetProperty(fields[0])), parameter);
Expression<Func<TSource, string>> field = Expression.Lambda<Func<TSource, string>>(expression, parameter);
return source.Like(field, textToFind);
}
现在这段代码不起作用! 我需要了解如何声明 Like 扩展方法的“字段”。
Expression<Func<TSource, string>> field = Expression.Lambda<Func<TSource, string>>(expression, parameter);
在运行时我收到此错误:Impossibile utilizzare un'espressione di Tipo 'System.Func`2[TestMdf.Equipment,System.String]' per un tipo restituito 'System.String'
【问题讨论】:
-
我对你的第二种扩展方法有点困惑。您遍历元素上的所有 PropertyInfo,将它们添加到字段集合中,然后只需选择第一个。这似乎真的很模糊和没有针对性......很可能会返回随机结果。在我提供任何答案之前……这是你想要的吗?或者你真的需要选择一个特定的属性来搜索......或者你需要遍历所有属性并为每个属性调用 .Like() 并聚合结果?
-
嗨,你对循环的看法是正确的......这个扩展方法的最终版本将生成几个 where 子句。例如,您有字段 F1、F2、F3 是数字或字符串,我想在这样的文本中搜索: ' ' + F1 + ' ' + F2 + ' ' + F3 + ' ' LIKE '%
%' 但是会更复杂...我想添加一个小搜索引擎:' ' + F1 + ' ' + F2 + ' ' + F3 + ' ' LIKE '% %' AND ' ' + F1 + ' ' + F2 + ' ' + F3 + ' ' LIKE '% %' AND ' ' + F1 + ' ' + F2 + ' ' + F3 + ' ' NOT LIKE '% % ' 并管理短语。
标签: c# linq entity-framework linq-to-entities lambda