C# 如何在lambda实体框架中进行动态排序?
我想在lambda实体框架中对动态进行排序。我花了更多时间创建了它,但似乎不起作用C# 如何在lambda实体框架中进行动态排序?,c#,entity-framework,sorting,lambda,sql-order-by,C#,Entity Framework,Sorting,Lambda,Sql Order By,我想在lambda实体框架中对动态进行排序。我花了更多时间创建了它,但似乎不起作用 ////string column_name // the name of column in table <<< don't care this, I finished ////string sort_order // ASC or DESC <<< don't care this, I finished using (var db = new ABCEntit
////string column_name // the name of column in table <<< don't care this, I finished
////string sort_order // ASC or DESC <<< don't care this, I finished
using (var db = new ABCEntities())
{
// get dynamic type of column name , but i can not
// ???????????
var columnExp = typeof(LOCATION).GetProperty(column_name);
IEnumerable<LOCATION> query = db.LOCATIONs;
if(sort_order = "ASC")
{
query = query.OrderBy(columnExp).Tolist();
}
else
query = query.OrderByDescending(columnExp).Tolist();
}
但是在
LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression
你能告诉我一些错误或错误以及如何纠正吗?
非常感谢。如何使用?
它可以从字符串生成查询
using (var db = new ABCEntities()){
var columnExp = "columnName";
var query = db.LOCATIONs;
if(sort_order = "ASC")
{
query = query.OrderBy(columnExp).Tolist();
}
else
{
query = query.OrderByDescending(columnExp).Tolist();
}
}
我试过了,但没用。@BrianCrist请说得更具体些。什么不起作用?我认为您应该简单地执行
OrderBy(column\u name)
,假设您使用的是动态LINQ。或者粘贴更多的代码?亲爱的kcwu,你的答案很有用,另外,我创建了一种方法,这个var-propertyInfo=typeof(LOCATION).GetProperty(columnName);query=db.LOCATIONs.AsEnumerable().OrderByDescending(x=>propertyInfo.GetValue(x,null)).ToList()代码>。非常感谢。
using (var db = new ABCEntities()){
var columnExp = "columnName";
var query = db.LOCATIONs;
if(sort_order = "ASC")
{
query = query.OrderBy(columnExp).Tolist();
}
else
{
query = query.OrderByDescending(columnExp).Tolist();
}
}