Dynamic sorting using Linq-to-Entities

c# entity-framework linq

Question

How can I use a string as an orderby parameter, is my question.

string sortColumn="Title";

var  items = (from ltem in ctxModel.Items
              where ltem.ItemID == vId
              orderby //something here
              select ltem).Skip(PageSize * PageIndex).Take(PageSize);

UPDATE:
Because I need to sort the result set and just need to page, I can't simply OrderBy the result set.

1
18
4/30/2010 9:26:20 PM

Accepted Answer

Using Dynamic link or other libraries, according to some, is advised. I wouldn't add a library requirement for such a simple job, Personally. But there are still two additional options available to you:

  • Build your query expression tree dynamically and use the Input Call syntax. For instance...

look at zzz-24 zzz

In this case, it's crucial to take Postponed Execution into account. You can create your query such that it produces a IQueryable object, and then you may sort the returned object using an object query. When the data is actually accessible, just one instance of your query will be executed.

The blog article mentioned above serves as an example of how to create an expression tree using the Expression API for your OrderBy. It just sounds challenging. The MSDN article could serve as a more useful guide. On MSDN, look up How to Create Dynamic Queries Using Expression Trees.

Or

  • Take the easy way out and limit your switch to the query's title.

Eg.

ItemType items = default(ItemType);
switch(sortColumn)
{
     case "Title":
     {
           items = ctxModel.Items
                    .Where(i => i.ItemID == vId)
                    .OrderBy( i => i.Title);
     }
     break;
 }
6
4/30/2010 11:23:24 PM

Popular Answer

I use this aid:

public static class OrderExt
{
    private static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName, SortDirection descending, bool anotherLevel = false)
    {
        var param = Expression.Parameter(typeof(T), string.Empty);
        var property = Expression.PropertyOrField(param, propertyName);
        var sort = Expression.Lambda(property, param);

        var call = Expression.Call(
            typeof (Queryable),
            (!anotherLevel ? "OrderBy" : "ThenBy") +
            (descending == SortDirection.Descending ? "Descending" : string.Empty),
            new[] {typeof (T), property.Type},
            source.Expression,
            Expression.Quote(sort));

        return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
    }
}

To contact the assistant, for instance, follow these steps:

string sort = HttpContext.Current.Request.QueryString["sort"];
var products = _productRepository.OrderBy(sort, SortDirection.Ascending);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow