C # EF Sort field dynamics, building dynamic lambda and extension methods

Source: Internet
Author: User
Tags reflection

1. Dynamically Build Sort Lambda

        /// <summary>        ///Get Sort lambda (if dynamic sort, different types will cause conversion to fail)/// </summary>        /// <typeparam name= "T" >data field type</typeparam>        /// <typeparam name= "Tkey" >sort Field Type</typeparam>        /// <param name= "DEFAULTSORT" >The default sort field</param>        /// <param name= "Sort" >Current Sort field</param>        /// <returns></returns>         Public StaticExpression<func<t, tkey>> sortlambda<t, tkey> (stringDEFAULTSORT,stringsort) {            //1. Create an expression parameter (specify the type of parameter or variable: p)            varparam = Expression.parameter (typeof(T),"T"); //2. Construct the expression body (the type contains the specified attribute: p.name)            varBODY = Expression.property (param,string. IsNullOrEmpty (sort)?defaultsort:sort); //3. Construct a lambda expression based on parameters and expression body            returnExpression.lambda<func<t, tkey>> (Expression.convert (Body,typeof(Tkey)), param); }

How to use:

         PublicIqueryable<t> getmodelsbypage<tkey> (intPageSize,intPageIndex,BOOLIsasc, Expression<func<t, tkey>> Orderbylambda, Expression<func<t,BOOL>> Wherelambda, out intTotal ) { Total= dbcontext.set<t>(). Where (WHERELAMBDA).            Count (); //whether ascending            if(ISASC) {returnDbcontext.set<t> (). Where (WHERELAMBDA). (ORDERBYLAMBDA). Skip ((PageIndex-1) *pageSize).            Take (pageSize); }            Else            {                returnDbcontext.set<t> (). Where (WHERELAMBDA). OrderByDescending (ORDERBYLAMBDA). Skip ((PageIndex-1) *pageSize).            Take (pageSize); }        }

Cons: TKey must be qualified, but do not necessarily know the field type, the wrong type will cause the conversion to fail, the tangent return value cannot be fixed to object, if there are other methods, I hope Daniel gives advice.

2. Extend the method of an out-of-the-way EF ( This method does not need to specify a type )

    /// <summary>    ///Query extension Methods/// </summary>     Public Static classqueryableextension { Public StaticIorderedqueryable<t> orderby<t> ( Thisiqueryable<t> Query,stringPropertyName) {            return_orderby<t> (Query, PropertyName,false); }         Public StaticIorderedqueryable<t> orderbydescending<t> ( Thisiqueryable<t> Query,stringPropertyName) {            return_orderby<t> (Query, PropertyName,true); }        StaticIorderedqueryable<t> _orderby<t> (iqueryable<t> query,stringPropertyName,BOOLIsdesc) {            stringMethodName = (ISDESC)?"orderbydescendinginternal":"orderbyinternal"; varMemberprop =typeof(T).            GetProperty (PropertyName); varMETHOD =typeof(queryableextension). GetMethod (methodname). MakeGenericMethod (typeof(T), memberprop.propertytype); return(iorderedqueryable<t>) method. Invoke (NULL,New Object[] {query, memberprop}); }         Public StaticIorderedqueryable<t> orderbyinternal<t, tprop> (iqueryable<t>query, System.Reflection.PropertyInfo memberproperty) {// Public            returnQuery. (_getlamba<t, tprop>(MemberProperty)); }         Public StaticIorderedqueryable<t> orderbydescendinginternal<t, tprop> (iqueryable<t>query, System.Reflection.PropertyInfo memberproperty) {// Public            returnQuery. OrderByDescending (_getlamba<t, tprop>(MemberProperty)); }        StaticExpression<func<t, tprop>> _getlamba<t, tprop>(System.Reflection.PropertyInfo memberproperty) {if(Memberproperty.propertytype! =typeof(Tprop))Throw NewException (); varThisarg = Expression.parameter (typeof(T)); varLamba = expression.lambda<func<t, tprop>>(Expression.property (Thisarg, MemberProperty), Thisarg); returnLamba; }    }

How to use:

         PublicIqueryable<t> Getmodelsbypage (intPageSize,intPageIndex,BOOLISASC,stringOrderbyfield, Expression<func<t,BOOL>> Wherelambda, out intTotal ) { Total= dbcontext.set<t>(). Where (WHERELAMBDA).            Count (); //whether ascending            if(ISASC) {returnDbcontext.set<t> (). Where (WHERELAMBDA). (Orderbyfield). Skip ((PageIndex-1) *pageSize).            Take (pageSize); }            Else            {                returnDbcontext.set<t> (). Where (WHERELAMBDA). OrderByDescending (Orderbyfield). Skip ((PageIndex-1) *pageSize).            Take (pageSize); }        }

Disadvantage: I can not understand!

C # EF Sort field dynamics, building dynamic lambda and extension methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.