Dex*_*ter 2 c# linq asp.net entity-framework
我正在尝试构建一个函数,以根据某些参数动态生成不同的查询.我对LINQ语法有点困惑,我不确定我是否做得对.
字符串类型参数的集合是"搜索"(对于搜索文本框值),"搜索字段"(要搜索的内容),"limit_begin","limit_end"表示行数和起始位置."order_by"为哪个字段排序."order_sort"以哪种方式排序.
我之前在stackoverflow上发现了这个'getpropertyvalue'反射函数,我希望它根据我自己的解释做我想要的.
private static object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
Run Code Online (Sandbox Code Playgroud)
if (order_sort == "ASC")
{
(from a in entities.UserTable
where GetPropertyValue(a, searchfield).ToString().Contains(search)
select a)
.OrderBy("a." + order_by)
.Skip(Convert.ToInt32(limit_begin))
.Take(Convert.ToInt32(limit_end))
.ToList();
}
else if (order_sort == "DESC")
{
(from a in entities.UserTable
where GetPropertyValue(a, searchfield).ToString().Contains(search)
select a)
.OrderByDescending("a." + order_by)
.Skip(Convert.ToInt32(limit_begin))
.Take(Convert.ToInt32(limit_end))
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
我在"Orderby"行上收到错误,而VS2008用红色突出显示错误,说明参数的类型无法从使用中推断出来.
该.OrderBy和.OrderByDescending方法需要类型的参数Func<T, TKey>和你传递一个字符串.基本上,它要求您提供一个表达式,它可以用来标识要排序的属性.因为你必须开始的是一个字符串,我最好的想法是在你的OrderBy中使用反射.
.OrderBy(x => x.GetType().GetProperty(order_by).GetValue(x, null).ToString())
正如您所看到的,这不是很容易阅读,但应该这样做.您还可以在以下网址查看LINQ动态查询库:http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query- library.aspx.
希望这可以帮助!:)