how to order by a dynamic column name in EntityFramework?

耗尽温柔 提交于 2019-12-12 20:30:07

问题


I am trying to get following code working , This was working fine for MSSQL , but since i changed to use mySql it is not working

  records.Content = db.areas
                         .Where(x =>   x.Name.Contains(filter)))
                         .OrderBy("dated desc") 
                         .ToList();

I get the error " Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information."

string colName = "datedD" ; 

how to order by depneding on colName variable ?
`


回答1:


Try this

string filterString = "dated";
bool isAscSorting = false;

Func<dynamic, dynamic> orderingFunction = i =>
                                filterString == "dated" ? i.dated :
                                filterString == "something" ? i.columnx : "";

records.Content = (isAscSorting) ?
                      db.areas
                         .Where(x =>   x.Name.Contains(filter)))
                         .OrderBy(orderingFunction) 
                         .ToList()
                   :
                        db.areas
                         .Where(x =>   x.Name.Contains(filter)))
                         .OrderByDescending(orderingFunction) 
                         .ToList();



回答2:


In asp.net mvc core 2, you can use the EF.Property method to specify the name of the property as a string:

string sortColumn = "Price";

//IQueryable<Product> q = from p in myDbContext.Products select p;
q = q.OrderBy(p => EF.Property<object>(p, sortColumn));

I'm not sure from which version we can use this.



来源:https://stackoverflow.com/questions/38055150/how-to-order-by-a-dynamic-column-name-in-entityframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!