Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 791803
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T21:53:45+00:00 2026-05-14T21:53:45+00:00

I’m trying to add the orderby expression on the fly. But when the query

  • 0

I’m trying to add the orderby expression on the fly. But when the query below is executed I get the following exception:

System.NotSupportedException: Unable
to create a constant value of type
‘Closure type’. Only primitive types
(‘such as Int32, String, and Guid’)
are supported in this context.

The strange thing is, I am query exactly those primitive types only.

string sortBy = HttpContext.Current.Request.QueryString["sidx"];
ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting");
Expression orderByProperty = Expression.Property(prm, sortBy);

// get the paged records
IQueryable<PostingListItemDto> query =
   (from posting in be.buskerPosting
    where posting.buskerAccount.cmsMember.nodeId == m.Id
    orderby orderByProperty
    //orderby posting.Created 
    select new PostingListItemDto { Set = posting }).Skip<PostingListItemDto>((page -   1) * pageSize).Take<PostingListItemDto>(pageSize);

Hope somebody can shed some light on this!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T21:53:45+00:00Added an answer on May 14, 2026 at 9:53 pm

    You basically can’t use query expressions like this, due to the way they’re translated. However, you can do it explicitly with extension methods:

    string sortBy = HttpContext.Current.Request.QueryString["sidx"];
    ParameterExpression prm = Expression.Parameter(typeof(buskerPosting), "posting");
    Expression orderByProperty = Expression.Property(prm, sortBy);
    
    // get the paged records
    IQueryable<PostingListItemDto> query = be.buskerPosting
        .Where(posting => posting.buskerAccount.cmsMember.nodeId == m.Id)
        .OrderBy(orderByExpression)
        .Select(posting => new PostingListItemDto { Set = posting })
        .Skip<PostingListItemDto>((page -   1) * pageSize)
        .Take<PostingListItemDto>(pageSize);
    

    The tricky bit is getting the right expression tree type – that’ll come in an edit 🙂

    EDIT: The edit will be somewhat delayed for various reasons. Basically you may need to call a generic method using reflection, as Queryable.OrderBy needs a generic Expression<Func<TSource, TKey>> and although it looks like you know the source type at compile-time, you may not know the key type. If you do know it’ll always be ordering by (say) an int, you can use:

    Expression orderByProperty = Expression.Property(prm, sortBy);
    var orderByExpression = Expression.Lambda<Func<buskerPosting, int>>
        (orderByProperty, new[] { prm });
    

    EDIT: Okay, it looks like I had time after all. Here’s a short example of calling OrderBy using reflection:

    using System;
    using System.Reflection;
    using System.Linq;
    using System.Linq.Expressions;
    
    public class Test
    {
        static void Main()
        {
            string[] names = { "Jon", "Holly", "Tom", "Robin", "Will" };
            var query = names.AsQueryable();
            query = CallOrderBy(query, "Length");
            foreach (var name in query)
            {
                Console.WriteLine(name);
            }
        }
    
        private static readonly MethodInfo OrderByMethod =
            typeof(Queryable).GetMethods()
                .Where(method => method.Name == "OrderBy")
                .Where(method => method.GetParameters().Length == 2)
                .Single();
    
        public static IQueryable<TSource> CallOrderBy<TSource>
            (IQueryable<TSource> source, string propertyName)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(TSource), "posting");
            Expression orderByProperty = Expression.Property(parameter, propertyName);
    
            LambdaExpression lambda = Expression.Lambda(orderByProperty, new[] { parameter });
            Console.WriteLine(lambda);
            MethodInfo genericMethod = OrderByMethod.MakeGenericMethod
                (new[] { typeof(TSource), orderByProperty.Type });
            object ret = genericMethod.Invoke(null, new object[] {source, lambda});
            return (IQueryable<TSource>) ret;
        }
    }
    

    You could easily refactor CallOrderBy into an extension method (e.g. OrderByProperty) like this:

    public static class ReflectionQueryable
    {
        private static readonly MethodInfo OrderByMethod =
            typeof(Queryable).GetMethods()
                .Where(method => method.Name == "OrderBy")
                .Where(method => method.GetParameters().Length == 2)
                .Single();
    
        public static IQueryable<TSource> OrderByProperty<TSource>
            (this IQueryable<TSource> source, string propertyName)
        {
            ParameterExpression parameter = Expression.Parameter(typeof(TSource), "posting");
            Expression orderByProperty = Expression.Property(parameter, propertyName);
    
            LambdaExpression lambda = Expression.Lambda(orderByProperty, new[] { parameter });
            Console.WriteLine(lambda);
            MethodInfo genericMethod = OrderByMethod.MakeGenericMethod
                (new[] { typeof(TSource), orderByProperty.Type });
            object ret = genericMethod.Invoke(null, new object[] {source, lambda});
            return (IQueryable<TSource>) ret;
        }    
    }
    

    Your original code then becomes:

    string sortBy = HttpContext.Current.Request.QueryString["sidx"];
    // get the paged records
    IQueryable<PostingListItemDto> query = be.buskerPosting
        .Where(posting => posting.buskerAccount.cmsMember.nodeId == m.Id)
        .OrderByProperty(sortBy)
        .Select(posting => new PostingListItemDto { Set = posting })
        .Skip<PostingListItemDto>((page -   1) * pageSize)
        .Take<PostingListItemDto>(pageSize);
    

    (Apologies for the formatting involving horizontal scrollbars… I’ll reformat later if anyone cares. Or you could do it for me if you have enough rep 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.