I ran into a LINQ problem around building queries dynamically. I could easily write something that was not type safe and not checked at compile time, but that bothered me. The whole point of using LINQ was to keep everything type safe and verified at compile time.
My case involved querying an entity rather than SQL directly, but the same rules applied.
The answer was lambda expressions. Because each Where call returns a new query rather than executing anything, you can build the query up conditionally and only run it at the end:
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
Each conditional adds a filter to the query without running it. Nothing hits the database until AsEnumerable is called at the end, so you get one query with exactly the filters the caller asked for, and all of it still type safe.