Working with Entity Framework (EF6) and VB.Net reflection, both of which I'm not super familiar with at this point.
Here's a brief example of what I'm trying to achieve:
Dim user as New user()
user.full_name = "John Smith"
Dim str As String = "The user's name is **full_name**."
'For each p As Property In user.Properties
' str = str.Replace("**" + p.Name + "**", p.Value)
'Next
OUTPUT: The user's name is John Smith.
However, the catch is that the object
is of an anonymous type. I'd like to be able to pass in any of my entity classes and dynamically replace property occurrences.
I've tried a whole lot and read a ton of questions here on SO, but I'm still having trouble - It's quite evident that I don't properly understand reflection just yet.
I'll supply my code below, as well as anything I've referenced. If anyone can push me in the right direction, I'd be more than grateful. Thanks.
System.Reflection.TargetParameterCountException: Parameter count mismatch.
Public Function MailMerge(htmlString As String, obj As Object)
Dim keyNames As New List(Of String)
Dim dictionaryData As New Dictionary(Of String, String)()
For Each p As System.Reflection.PropertyInfo In obj.GetType().GetProperties()
If p.CanRead Then
Dim columnName As String = p.Name
'FAILS HERE - p.Name is "Item" at the failing iteration
Dim columnValue = p.GetValue(obj, Nothing)
dictionaryData.Add(columnName, columnValue)
End If
Next
For Each key In dictionaryData.Keys
htmlString = htmlString.Replace("**" + key + "**", dictionaryData(key))
Next
Return htmlString
End Function
References:
- How to iterate through each property of a custom vb.net object?
- How to loop through all the properties of a class?
- How to iterate through a property of a class in VB?
Aucun commentaire:
Enregistrer un commentaire