我使用 EF Codefirst 创建了一个 VB.net WinForms 程序和一个数据库。在其中一个表“Categories”中,有一个名为“ParentCategory_CategoryId”的列,它是该特定类别的父类别(nb 它可以为 NULL)。这使我可以无限量地嵌套子类别。到目前为止,一切都很好(下面的类别定义):
Public Class Category
Public Property CategoryId As Integer
Public Property CategoryName As String
Public Overridable Property ChildCategories As List(Of Category)
Public Overridable Property ParentCategory As Category
End Class
当我尝试使用此数据填充 TreeView 控件时,就会出现问题。我的意图是递归遍历类别并为每个类别添加一个 TreeNode,并为每个子类别添加一个子节点。VB代码如下:
Private Sub Categories_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create new data context
Dim dc As New MyContext
' Call the recursive function once with Parent category as nothing
LoadNodesOntoTreeview(dc, Nothing, Nothing)
End Sub
Public Sub LoadNodesOntoTreeview(dc As MyContext, Optional ParentCategory As Category = Nothing, Optional ByRef ParentNode As TreeNode = Nothing)
Try
For Each c As Category In dc.Categories.Where(Function(x) x.ParentCategory Is ParentCategory).ToList
Dim n As New TreeNode With {.Text = c.CategoryName}
LoadNodesOntoTreeview(dc, c, n)
If ParentNode Is Nothing Then
TreeView1.Nodes.Add(n)
Else
ParentNode.Nodes.Add(n)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
对于第一次迭代(ParentCategory = Nothing),这可以正常工作,但是在调用时会出现问题
LoadNodesOntoTreeview(dc, c, n)
自身内。我得到错误:
"Unable to create a constant value of
type 'System.Data.Entity.DynamicProxies.Category_D3161C0FA58DECDDCD3237
36A77B49BF9AC13F6AB1D9C56D7946173054210834'. Only primitive types or
enumeration types are supported in this context."
任何想法将不胜感激。