c# - Getting InvalidCastException when trying to implement sorting in Entity Framework Code First using Linq -
i have method below filterquery sorts data based on sortpropertyname property.
private iqueryable<tentity> filterquery(expression<func<tentity, bool>> predicate, string sortpropertyname, orderby orderby = orderby.ascending) { iqueryable<tentity> entities = _dbentityset; entities = (predicate != null) ? entities.where(predicate) : entities; if (string.isnullorempty(sortpropertyname)) { sortpropertyname = "id"; } var keyselector = createselectorexpression<tentity>(sortpropertyname); entities = (orderby == orderby.ascending) ? entities.orderby(keyselector) : entities.orderbydescending(keyselector); return entities; }
aforementioned method in turn calls method createselectorexpression .
private static expression<func<tentity, string>> createselectorexpression<tentity>(string propertyname) { try { var paramterexpression = expression.parameter(typeof(tentity)); return (expression<func<tentity, string>>)expression.lambda(expression.propertyorfield(paramterexpression, propertyname), paramterexpression); } catch (exception ex) { string msg = ex.tostring(); return null; } }
the above solution works fine when property of type string throw exception in case if property type numeric or date time. time being can see have hard-coded id property raise exception. here exception createselectorexpression throws when returning expression:
unable cast object of type 'system.linq.expressions.expression1[system.func
2[myproject.business.domain.myclass,system.int32]]' type 'system.linq.expressions.expression1[system.func
2[myproject.business.domain.myclass,system.string]]
can please me going on wrong in code or better soltion? please let me know if required more information me.
instead of building , expression scratch, can take expression on tentity
key selector in place of sortpropertyname
parameter :
private iqueryable<tentity> filterquery<tvalue>(expression<func<tentity, bool>> predicate, expression<func<tentity, tvalue>> sortexpression, orderby orderby = orderby.ascending) { iqueryable<tentity> entities = _dbentityset; entities = (predicate != null) ? entities.where(predicate) : entities; entities = (orderby == orderby.ascending) ? entities.orderby(sortexpression) : entities.orderbydescending(sortexpression); return entities; }
you can remove createselectorexpression
function.
example of use :
filterquery<test>(p => p.id > 50, p => p.id, orderby.ascending)
will filter result item having id
greater 50 , sort them id
property.
Comments
Post a Comment