Wednesday, 19 November 2008

Dynamically adding where and order by clauses

This is great for creating dynamic queries which have optional where parameters. This example is using linq to entities in the data service rather than on the client


Dim c As IQueryable(Of Model.Customer) = (From cust In ctx.Customer)

If strSurname.Length > 0 Then
c = c.Where(Function(a) a.Surname.StartsWith(strSurname))
End If

If strForename.Length > 0 Then
c = c.Where(Function(a) a.Forename.StartsWith(strForename))
End If


Dim c_ordered As IOrderedQueryable(Of Model.Customer) = c
c_ordered = c_ordered.OrderByDescending(Function(p) p.DateTimeModified)

I also sort the query so linq to entities can use the skip function. The skip function throws an error otherwise.

No comments: