Dynamic OrderBy in a LINQ query

Thread is closed for posting
2 posts, 0 answers
  1. Joseph S.
    Joseph S. avatar
    11 posts
    Member since:
    Dec 2008

    Posted 28 Apr 2015 Link to this post


    I need to build a dynamic LINQ query (VB.NET) where the sort field must be build as string at runtime. My query is like this:

    Dim lobjQueryGenData As IQueryable(Of clsDmlEO) = From GenData In ObjectScope.Extent(Of clsDmlEO)() Select GenData Where GenData.SessionId = pstrSessionId
    lobjQueryGenData = lobjQueryGenData.OrderBy(Function(GenData) GenData.RowId)

    clsDmlEO is a "<Telerik.OpenAccess.Persistent()> <Serializable()>" class mapped to SQL Server table.

    I need to change the OrderBy in something like this:

    lobjQueryGenData = lobjQueryGenData.OrderBy(pstrSortField)
    where pstrSortField is a string variabile/parameter built at runtime.

    Please can you help me?

  2. Simeon Simeonov
    Simeon Simeonov avatar
    24 posts

    Posted 01 May 2015 Link to this post

    Hello Joseph,

    Thank you for contacting us.

    What you need is easily accomplished using Microsoft's Dynamic Query Library together with Open Access. There is a blog post discussing the topic here.

    What you need to do is add to your project the Microsoft's DynamicQuery NuGet package. You can find it by searching for "DynamicQuery" or "Dynamic Expression Api" in the NuGet package manager.

    I have prepared example for ordering some forum posts by "Id" or by "DateCreated":

    Imports Forum.Data
    Imports System.Linq.Dynamic
    Namespace Example
        Class TestMain
            Private Shared Sub Main(args As String())
                Using context = New ForumFluentModel()
                    Dim orderedForumPostsById = context.ForumPosts.OrderBy("Id")
                    Dim orderedForumPostsDateCreated = context.ForumPosts.OrderBy("DateCreated")
                End Using
            End Sub
        End Class
    End Namespace

    Please note the imported System.Linq.Dynamic namespace. You will need this because in it is the class holding the OrderBy extension method of IQueryable you need.

    I hope you find this information helpful.

    Simeon Simeonov
    OpenAccess ORM is now Telerik Data Access. For more information on the new names, please, check out the Telerik Product Map.
Back to Top