Not sure if I am using the correct term, but it's not child/parent since they aren't nested objects. In my application I've got a User, UserUserGroup, and UserGroup objects which are pretty standard, UserUserGroup is a linking object with corresponding IDs. I am using Linq-to-SQL so unforunately it doesn't used nested objects, but it still knows the relation.
Consider the following class and query where I am trying to return a list of Users that are associated with a specific UserGroup:
Public Class UserDao
Inherits EntityDao(Of User)
Public Function getListOfUsersByUserGroupName(ByVal userGroupName As String) As IList(Of User)
Dim userList As New List(Of User)
If Not userGroupName Is Nothing Then
Dim userGroupDao As New UserGroupDao()
Dim userUserGroupDao As New UserUserGroupDao()
Dim userGroup As New UserGroup()
userGroup = userGroupDao.getOneByValueOfProperty("Name", userGroupName)
If Not userGroup Is Nothing Then
Dim userUserGroup As IQueryable(Of UserUserGroup) = userUserGroupDao.getListByValueOfProperty("UserGroupId", userGroup.Id)
If Not userUserGroup Is Nothing Then
Dim userDao As New UserDao()
Dim user As New User()
For Each entry As UserUserGroup In userUserGroup
Dim result As UserUserGroup = entry
user = userDao.getOneByValueOfProperty("Id", result.Id)
userList.Add(user)
Next
End If
End If
End If
Return userList
End Function
End Class
Is there anyway to make this better with less lines and more efficient? It seems incredibly inefficient for me to first get the ID of the supplied usergroup, then get the results in UserUserGroup where UserGroupId equals that, then get all the User Ids from that query and then for each of those Ids, query the User table to grab the object corresponding to that ID. It just seems bad for one 'result' I am running at least 3 queries, with each of them creating and disposings dataContexts. It seems like it would be taxing, especially on the for each loop if there was a ton of results returned.