EF Codefirst を使用して VB.net WinForms プログラムとデータベースを作成しました。テーブルの 1 つである "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."
どんなアイデアでも大歓迎です。