我想确定调用该方法时接收到的特定对象的属性,并根据获得的数据库结果将值放入其中。我已经搜索过它,但是我目前仍停留在应该如何从这里开始的问题上。这是我的代码。
Public Class DBModel
Public Sub getFromDB(ByRef lists As List(Of Object), ByVal classType As Type, ByVal tblName as String)
Dim strSql As String = "SELECT * FROM " & tblName
Dim props = classType.GetProperties()
Try
Using cnn As New SqlConnection("Data Source = .\; Initial Catalog = DBName;" & "Integrated Security = True;")
Using cmd As New SqlCommand(strSql, cnn)
cnn.Open()
Using dr As SqlDataReader = cmd.ExecuteReader()
While dr.Read
For Each prop In props
For i As Integer = 0 To dr.VisibleFieldCount - 1
prop = dr.GetValue(i)
Next
Next
lists.Add(props)
End While
End Using
End Using
End Using
Catch e As Exception
MessageBox.Show(e.ToString())
End Try
End Sub
End Class
我在这里调用getFromDB方法来填充此类中的客户列表,但是我还将从具有其他不同属性集的其他类中调用getFromDB方法。.
Public Class CustomerCtrler
private _CustomerList As New List(Of Customer)
Public Sub New()
Dim dbModel As New DBModel
Dim cust As New Customer
dbModel.getFromDB(_CustomerList, cust.GetType, "CustTbl")
End sub
End Class
Public Class Customer
Public Property custID As Integer
Public Property FirstName As String
Public Property LastName As String
Public Property DateRegistered As DateTime
End Class
但是我有一个InvalidCastException,所以我搜索了有关转换数据类型的信息,但是我得到:“ prop = dr.GetValue(i)”行的“ Integer的值类型无法转换为PropertyInfo”。 / p>
我对面向对象的编程还很陌生,所以如果在那里有很多错误,对不起,但是您的帮助将不胜感激。
答案 0 :(得分:1)
我倾向于使用这样的东西:
Public Function GetListFromDatabase(Of T As New)(tableName As String) As List(Of T)
Dim itemType = GetType(T)
Dim allProperties = itemType.GetProperties()
Dim items As New List(Of T)
Using connection As New SqlConnection("connection string here"),
command As New SqlCommand($"SELECT * FROM [{tableName}]", connection)
connection.Open()
Using reader = command.ExecuteReader()
Dim columnNames = reader.GetColumnSchema().
Select(Function(column) column.ColumnName).
ToArray()
'Ignore properties that don't have a corresponding column.
Dim properties = allProperties.Where(Function(prop) columnNames.Contains(prop.Name)).
ToArray()
Do While reader.Read()
'We can do this because we have specified that T must have a
'parameterless constructor by using "As New" in the method declaration.
Dim item As New T
For Each prop In properties
prop.SetValue(item, reader(prop.Name))
Next
items.Add(item)
Loop
End Using
End Using
Return items
End Function
然后您可以执行以下操作:
_CustomerList = dbModel.GetListFromDatabase(Of Customer)("CustTbl")
如果您确实想传递现有列表,显然可以在此基础上创建变体,但是除非列表可能已经包含项目,否则我看不出要点。
编辑:这是获取数据读取器列名称的另一种方法。我尚未测试过,因此可能是“ COLUMN_NAME”不太正确,但这将与之非常接近:
Dim schemaTable = reader.GetSchemaTable()
Dim columnNames = schemaTable.Rows.
Cast(Of DataRow).
Select(Function(row) CStr(row("COLUMN_NAME"))).
ToArray()