Я пытаюсь изучить Entity Framework, чтобы попытаться перейти от Linq к SQL, и моя попытка преобразовать некоторый код не удалась для рекурсивной таблицы «многие ко многим» (древовидная структура). Мне нужно выполнить полное чтение таблицы и подготовить дерево в памяти, потому что повторение через базу данных с большим количеством запросов происходит слишком медленно.
У меня есть база данных с таблицей Projects и другая таблица с именем ProjectsTree. С Linq до SQL я могу получить доступ к таблице ProjectsTree, но не с Entity Framework. Он связывает его так, что я не могу напрямую запросить эту таблицу.
Вот код, прежде чем я попытался преобразовать Linq в SQL в Entity Framework, и это сработало. Может быть, я должен придерживаться Linq до SQL и не узнавать что-то новое, и если нет никакого способа сделать это, я могу go назад или позволить двум сосуществовать.
Private Class cProjectTree2
Public Project As PDMVault.Project
Public ChildTree As List(Of cProjectTree2)
End Class
''' <summary>
''' Gets the complete PDM project tree that can be added to a tree node.
''' Each node has the description in the node text field and the primary key in the tag.
''' </summary>
''' <returns></returns>
Public Function GetPDMProjectTree() As TreeNode
' To generate the tree, first read the projects table with a complete table scan, then the ProjectTree with a complete table scan.
' Create a dictionary of objects of type cRecursiveProjectTree, but only the project is set on the first pass, with a reference to it based on its key.
' After the dictionary is built, then link up children to parent using the dictinary.
' Finally, use the created tree to create the node structure for the tree view.
Dim Diag_Stopwatch As New Stopwatch
Dim IDtoTree As New Generic.Dictionary(Of Long, cProjectTree2)
Dim C = New PDMVault.DataContext1
' C.Log = Console.Out
Dim Projects = C.Projects.ToList ' Database list of trees.
''''''''''''''''''''''This is the line that fails. ProjectTrees only shows up as an association, and I can't seem to get access to it for a full table scan
Dim Tree = C.ProjectTrees.ToList ' Database hierarcy of the projects in the previous statement
'''''''''''''''''''''''''''''''''''''''''''''
' Create the dictionary with only the "Project" item set
For Each P In Projects
Dim ProjectTreeEntry As New cProjectTree2
ProjectTreeEntry.ChildTree = New List(Of cProjectTree2)
ProjectTreeEntry.Project = P
IDtoTree.Add(P.ProjectID, ProjectTreeEntry)
Next
' Now that the dictionary has been created, the children can be linked to the parent.
For Each T In Tree
Dim Parent As cProjectTree2 = Nothing
Dim Child As cProjectTree2 = Nothing
IDtoTree.TryGetValue(T.ProjectID, Parent)
IDtoTree.TryGetValue(T.ChildProject, Child)
Parent.ChildTree.Add(Child)
Next
' The tree has been built, create the tree view from the tree (using a little recursion)
Dim GetChildTrees As Func(Of cProjectTree2, TreeNode) =
Function(P As cProjectTree2) As TreeNode
Dim Result As New TreeNode
For Each Child In P.ChildTree.OrderBy(Function(ProjectNode) ProjectNode.Project.Name)
Dim N = GetChildTrees(Child)
If N IsNot Nothing Then
Result.Nodes.Add(N)
End If
Next
Result.Tag = P.Project.ProjectID
Result.Text = P.Project.Name
Return Result
End Function
Dim RootProject As cProjectTree2 = Nothing
If IDtoTree.TryGetValue(1, RootProject) = True Then
Dim N2 As TreeNode = GetChildTrees(RootProject)
Return N2
Else
Return Nothing
End If
End Function