I'm pretty new to LINQ to SQL and have come across a problem with dynamic Where clauses and Joins. For exampe, if I have 2 parameters, one of them optional, I need to find a way to include/exclude the optional parameter from my query. In SQL I would build
up statement as a string and then execute it. I have read an example by ScottGU - http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx - which handles a single table but I can't find a way to do this
with multiple joins.
Here is the code I am using
Public Function GetCompByFacilityID(ByVal intFacilityID As Integer, ByVal strUsername As String) As Object
Dim dc As New DCMainDataContext
Dim query1 = Nothing
Try
query1 = (From cmp In dc.CMP_Comp _
Join fac In dc.Facilities On cmp.FacilityID Equals fac.FacilityID _
Join usrfac In dc.UserFacilities On fac.FacilityID Equals usrfac.FacilityID _
Join cmpfrm In dc.LU_FormOfComp On cmp.FormComplimentID Equals cmpfrm.FormComplimentID _
Where usrfac.Username = strUsername And fac.FacilityID = intFacilityID _
Select cmp.FacilityID, fac.FacilityName, cmp.CompDate, cmpfrm.FormComp, cmp.ReceivedFrom _
Order By FacilityName).ToList
Catch ex As Exception
Throw ex
Finally
dc = Nothing
End Try
Return query1
End Function
If the value of intFacility ID is -1 I want to exclude this from the statement altogether. Does anyone have an example of how to do this?
blued
Member
125 Points
163 Posts
VB.NET LINQ to SQL Dynamic Where Clause and Joins
Apr 12, 2012 02:01 PM|LINK
I'm pretty new to LINQ to SQL and have come across a problem with dynamic Where clauses and Joins. For exampe, if I have 2 parameters, one of them optional, I need to find a way to include/exclude the optional parameter from my query. In SQL I would build up statement as a string and then execute it. I have read an example by ScottGU - http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx - which handles a single table but I can't find a way to do this with multiple joins.
Here is the code I am using
Public Function GetCompByFacilityID(ByVal intFacilityID As Integer, ByVal strUsername As String) As Object Dim dc As New DCMainDataContext Dim query1 = Nothing Try query1 = (From cmp In dc.CMP_Comp _ Join fac In dc.Facilities On cmp.FacilityID Equals fac.FacilityID _ Join usrfac In dc.UserFacilities On fac.FacilityID Equals usrfac.FacilityID _ Join cmpfrm In dc.LU_FormOfComp On cmp.FormComplimentID Equals cmpfrm.FormComplimentID _ Where usrfac.Username = strUsername And fac.FacilityID = intFacilityID _ Select cmp.FacilityID, fac.FacilityName, cmp.CompDate, cmpfrm.FormComp, cmp.ReceivedFrom _ Order By FacilityName).ToList Catch ex As Exception Throw ex Finally dc = Nothing End Try Return query1 End FunctionIf the value of intFacility ID is -1 I want to exclude this from the statement altogether. Does anyone have an example of how to do this?