c# - Better way to Sort a Queryable by any property -


this case similar better way sort list property, in case doesn't has list in memory before execute method '.tolist()'.

i want sort before database query executed. want 'write' sql query before execution.

my code:

public virtual datatablesdata<tviewmodel> datatablesgetdata(datatablesparam model) {     var paged = new datatablesdata<tviewmodel>();     iqueryable<tentity> qr;      try     {         using (var db = new edmxmssqlcontainer())         {             list<tviewmodel> list = null;              qr = db.set<tentity>();              int icolumn = model.order.firstordefault().column;             var property = typeof(tentity).getproperty(model.columns.toarray()[icolumn].data);             var param = expression.parameter(typeof(tentity));             expression final = expression.property(param, property);              if (property.propertytype.isvaluetype)             {                 final = expression.makeunary(expressiontype.convert, final, typeof(object));             }              var lambda = expression.lambda<func<tentity, object>>(final, param);              if (model.order.firstordefault().dir.equals("asc"))             {                 qr = qr.orderby(lambda);             }             else             {                 qr = qr.orderbydescending(lambda);             }              // line throw exception             // qr.tolist() execute sql query             list = mapper.map(qr.tolist(), list);              paged.recordstotal = this.countrecords();             paged.recordsfiltered = list.count();             paged.data = list;         }     }     catch (exception ex)     {         onerror(ex);     }      return paged; } 

this line throw exception:

list = mapper.map(qr.tolist(), list); 

exception:

unable cast type system.int32 type system.object. linq entities supports casting edm primitive or enumeration types

i found better way this. had steps:

1 - add package "linq dynamic" in project:

install-package system.linq.dynamic.library 

2 - import package in class:

using system.linq.dynamic; 

3 - order queryable string name of property:

qr.orderby(stringpropertyname);                 //asc qr.orderby(stringpropertyname + " descending"); //des 

it work me.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -