Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Expression for Paging / Pagination with dynamic OrderBy

All,

I am trying to get paging working with a grid. In order to do this, I have to pass in which field to sort by. I cannot figure out how to do this with a Linq query. I am using .NET 4 / EF 4.1. In the two examples below, #1 works just fine. The problem is, I am passing in the field to sort by, and so I need to be able to dynamically change what we are sorting by. When I try to use a string as in example 2, it does not sort by my expression. Is there any way to accomplish this? It seems like lots of people should need this functionality.

    [Example 1]
(from e in _context.MyEntity
 where (MyWhereClause)
 orderby e.SomeProperty Ascending
 select e).Skip(Offset).Take(MyCountPerPage);

    [Example 2]
(from e in _context.MyEntity
 where (MyWhereClause)
 orderby "SomeField, ASC"
 select e).Skip(Offset).Take(MyCountPerPage);

-Thanks-

like image 458
RepDetec Avatar asked Nov 27 '25 09:11

RepDetec


1 Answers

Use Dynamic LINQ

like image 144
Paul Creasey Avatar answered Nov 28 '25 23:11

Paul Creasey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!