I am trying to make a LINQ request in which I can change the field (one) by which I want to sort. Using a predicate variable allows this
public void GetMyData(string sortFieldName) { Func<MyEntity, object> orderPredicate = null; switch (sortFieldName) { case "FIELD_STRING": orderPredicate = x => x.FIELD_STRING; case "FIELD_INT": orderPredicate = x => x.FIELD_INT; case "FIELD_DATE": orderPredicate = x => x.FIELD_DATE; default: orderPredicate = x => x.FIELD_DATE; } var queryResult = db.MyEntity.OrderBy(orderPredicate); //...some logic } But dramatically (tenfold), the performance drops as compared with the direct assignment of the sort condition. As far as I understand, Expression should help. I change the type of variable
Expression<Func<MyEntity, object>> orderPredicate = null; But in rantayma gives an exception
Failed to cast type "System.DateTime" to type "System.Object". LINQ to Entities only supports the rendering of EDM primitive types or enumeration types.
How to be? After all, if I use the direct task conditions
public void GetMyData(string sortFieldName) { var query = db.MyEntity; var orderedQuery = query.OrderBy(x => x.FIELD_DATE); switch (sortFieldName) { case "FIELD_STRING": orderedQuery = query.OrderBy(x => x.FIELD_STRING); break; case "FIELD_INT": orderedQuery = query.OrderBy(x => x.FIELD_INT); break; case "FIELD_DATE": orderedQuery = query.OrderBy(x => x.FIELD_DATE); break; } //...some logic } , it will be difficult for me to complicate the request with additional Where , Include , etc. instructions.
IEnumerablesorting will occur on the client - Andrey NOPorderedQueryand add any of yourWhereandInclude:orderedQuery.Where(x => x.IntProp == 1)- Andrey NOP