EF6 查询 ToDictionary,键为 FieldName,值为 属性 VB.NET 中的值

EF6 Query ToDictionary with Key as FieldName and Value as Property Value in VB.NET

我的数据库

id UserName       UserLevel       UserEmail
-- -------------- --------------- -----------------
 1 JohnDoe        1               johndoe@acme.com
 2 UserTest       2               linda@acme.com

我的查询:

Dim MyQuery = (From U in DB.Users _
               Select U).FirstOrDefault

我在VB.NET中需要完成的是:

字典 "KeyValuePair" 输出所有 "Entity Properties Name" 和各自的值:

DBFieldName, Value of Row
------------  ----------------
Username    , johndoe
UserLevel   , 1
UserEmail   , johndoe@acme.com

想象一下,如果您需要生成具有此布局的文本文件(第一个数字是行号):

1: Username, johndoe
2: UserLevel, 1
3: UserEmail, johndoe@acme.com

到目前为止我有:

Dim MyQuery = (From U in DB.Users _
                   Select U).FirstOrDefault

Dim mydict As EFDictionary = ToEFDictionary(Of Users)(MyQuery)


<System.Runtime.CompilerServices.Extension()> _
Public Function ToEFDictionary(Of T)(ByVal Source As IEnumerable(Of T)) As EFDictionary
    Dim EFDictionary As New EFDictionary
    Dim Item As T
    For Each Item In Source
        Dim Properties = Item.GetType().GetProperties
        For Each p In Properties
            Try
                EFDictionary.Add(p.Name, p.GetValue(Item)) ' Loading Lazy Table, I need to Qualify these Properties before add, otherwise will load all the lazy tables.
            Catch ex As Exception
                Throw New Exception("Error loading Lazy Table")
            End Try
        Next
    Next
    Return EFDictionary
End Function


Public Class EFDictionary
    Inherits Dictionary(Of String, String)
    Public Sub New()
        MyBase.New()
    End Sub
    Public Sub New(ByVal dictionary As IDictionary(Of String, String))
        MyBase.New(dictionary)
    End Sub
End Class

我进行了编辑以支持直接从 Object 继承的匿名类型。 以同样的方式,您可以将它用于每个 class,因为它继承自 Object,而 GetType() 是一个对象方法。

你可以使用反射。

一个例子:

Imports System.Collections.Generic
Imports System.Reflection

Module Module1

    Sub Main()
        Dim cls As TestClass = New TestClass()

        cls.First = "Test"
        cls.Second = 125

        Dim result As List(Of String) = New List(Of String)()

        result = GetPropertiesNamesAndValues(cls, result)

        Dim product = New With {Key .Name = "paperclips", .Price = 1.29}

        result = GetPropertiesNamesAndValues(product, result)

        Dim count As Integer = 1
        For Each r In result
           Console.WriteLine("{0}, {1}", count, r)
           count += 1
        Next
        Console.ReadLine()
    End Sub

    Public Function GetPropertiesNamesAndValues(cls As Object, res As List(Of String)) As List(Of String)
        Dim props As PropertyInfo() = cls.GetType().GetProperties()

        For Each p As PropertyInfo In props
            res.Add(String.Format("{0} , {1}", p.Name, p.GetValue(cls, Nothing).ToString()))
        Next

       Return res
    End Function
End Module

其中 TestClass 由一对属性组成:

Public Class TestClass
    Private _first As String
    Private _second As String

    Public Property First As String
        Get
            Return _first
        End Get
        Set(value As String)
            _first = value
        End Set
    End Property

    Public Property Second As String
        Get
            Return _second
        End Get
        Set(value As String)
            _second = value
        End Set
    End Property
End Class

您需要做的就是遍历此 List(Of String) 文件。它必须是您传递给此函数的 class 的实例。

Public Function GetPropertiesNamesAndValues(Of TClass As Class)(cls As TClass) As List(Of String)
  Dim result As New List(Of String)
  Dim props As PropertyInfo() = cls.GetType().GetProperties()
  For Each p As PropertyInfo In props
    result.Add(String.Format("{0} {1}", p.Name, p.GetValue(cls, Nothing)))
  Next
  Return result
End Function

用法:

Dim user = (From U In DB.Users Where U.UserLevel = 1).FirstOrDefault
If Not user Is Nothing Then
  Dim userInfo = GetPropertiesNamesAndValues(user)
  'print results
End If