This is a migrated thread and some comments may be shown as answers.
Dynamic OrderBy in a LINQ query
1 Answer 12 Views
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Joseph S.
Top achievements
Rank 1
Joseph S. asked on 28 Apr 2015, 08:04 PM

Hello,

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?

1 Answer, 1 is accepted

Sort by
0
Simeon Simeonov
Telerik team
answered on 01 May 2015, 06:52 AM
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.

Regards,
Simeon Simeonov
Telerik
 
OpenAccess ORM is now Telerik Data Access. For more information on the new names, please, check out the Telerik Product Map.
 
Tags
LINQ (LINQ specific questions)
Asked by
Joseph S.
Top achievements
Rank 1
Answers by
Simeon Simeonov
Telerik team
Share this question
or