实体框架:通过导航属性名称字符串访问子实体

时间:2015-04-14 00:03:34

标签: vb.net entity-framework

我正在使用实体框架6(数据库优先)。

当我有一个对象时,我可以像这样访问它的Childs:

For each chld in Myobject.Child1
..... do something with chld.....
Next.

但是,假设我有一个对象作为变量(Varobj1),并且在列表(Navig_list)中,我有一些导航属性的名称:

{"Child1","Child2"}

我怎样才能做到与上面相同的事情:

For each str in Navig_list
   For each chld in ?????? ( Varobj1.????? )
   ..... do something with chld.....
   Next
Next

那么在这种情况下如何访问子集合呢? 谢谢!

1 个答案:

答案 0 :(得分:0)

亚历,

以下是使用CallByName的示例(请参阅上一个答案中的评论)。这对我来说很成功。

Private Sub TestCallByName()
    Dim r = New Root
    r.Child1.Add(New Grover With {.x = "Cleveland", .y = "Monkey"})

    Dim h = CallByName(r, "Child1", CallType.Get, {})

    Dim enumerator = CType(CallByName(h, "GetEnumerator", CallType.Method, {}), IEnumerator)

    Do
        If Not enumerator.MoveNext Then
            Exit Do
        End If

        Dim element = enumerator.Current

        Dim x = CallByName(element, "x", CallType.Get, {})
        Dim y = CallByName(element, "y", CallType.Get, {})

        Debug.Print(String.Format("{0}:{1}", x, y))
    Loop
End Sub

Private Class Root
    Public Child1 As New HashSet(Of Grover)
End Class

Private Class Grover
    Public x As String
    Public y As String
End Class