Tuesday, May 6, 2008

LINQ Dynamic Queries

I came across an article this morning that helped me with a LINQ query issue that I was trying to work through regarding dynamic queries.
 
 
My situation was very similar; however, in my case I was querying an ENTITY rather than SQL directly; however, the same rules applied.
 
I knew I could easily write a query that was not type safe and not checked at compile time; however, the thought of doing that really bothered me because I wanted to leverage the full power of LINQ and keep everything type safe and checked at compile time.
 
I ended up taking advantage of Lambda Expressions:

Public
Function Search(ByVal Name As String, ByVal City As String) As IEnumerable(Of MyTable)
    
Dim MyEntities As New DbEntities()
    
Dim MyQuery As ObjectQuery(Of MyTable) = MyEntities.MyTableSet
    
Dim MyResults = From x In MyQuery Select x

    
If Not IsBlank(Name) Then
         
MyResults = MyResults.Where(Function(e) e.Name.Equals(Name))
    
End If
 
     If Not IsBlank(City) Then
         
MyResults = MyResults.Where(Function(e) e.City.Equals(City))
    
End If

    
Return MyResults.AsEnumerable
End Function
 
More information on Lambda Expressions can be found here:
 

0 comments: