【发布时间】:2010-09-13 18:45:53
【问题描述】:
我从 CodePlex 上的这个示例中的 IQueryable 扩展方法开始。
我认为我需要的是“Where”的 IQueryable 扩展方法,其中方法签名如下所示:
public static IQueryable<T> Where<T>(this IQueryable<T> source, string columnName, string keyword)
并且有效地做到了这一点(假设 T.columnName 是字符串类型):
source.Where(p => p.ColumnName.Contains("keyword"))
使用上面的 CodePlex 示例,我想我理解他是如何让 OrderBy 方法工作的,但我的问题似乎有点复杂,我不知道如何让 Contains("keyword") 部分工作。
提前致谢,
--埃德
更新:太平洋标准时间 2010 年 9 月 13 日下午 6:26
我认为以下方法可行,但当我通过 Count() 执行表达式时,最终得到了 NotSupportedException(LINQ to Entities 不支持 LINQ 表达式节点类型“Invoke”。)。有什么想法吗?
public static IQueryable<T> Where<T>(this IQueryable<T> source, string columnName, string keyword)
{
var type = typeof(T);
var property = type.GetProperty(columnName);
if (property.PropertyType == typeof(string))
{
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var sel = Expression.Lambda<Func<T, string>>(propertyAccess, parameter);
var compiledSel = sel.Compile();
return source.Where(item => compiledSel(item).Contains(keyword));
}
else
{
return source;
}
}
【问题讨论】:
-
你解决过“LINQ to Entities 不支持”的问题吗?
标签: c# lambda extension-methods