Expanding on this answer I came up with the following to dump a Linq to SQL query into a csv format:
Public Shared Function ObjectsToCsvData(ByVal objs As IEnumerable(Of Object)) As String
If objs Is Nothing Then
Throw New ArgumentNullException("obj", "Value can not be null or Nothing!")
End If
Dim sb As StringBuilder = New StringBuilder()
Dim firstObj As Object = objs.First
Dim t As Type = firstObj.[GetType]()
Dim pi As PropertyInfo() = t.GetProperties(BindingFlags.DeclaredOnly Or BindingFlags.Public Or BindingFlags.Instance)
For index As Integer = 0 To pi.Length - 1
If Not pi(index).GetAccessors()(0).IsVirtual Then
sb.Append(pi(index).Name)
sb.Append(",")
End If
Next
sb.Remove(sb.Length - 1, 1)
sb.Append(vbCrLf)
For Each obj As Object In objs
For index As Integer = 0 To pi.Length - 1
If Not pi(index).GetAccessors()(0).IsVirtual Then
sb.Append(pi(index).GetValue(obj, Nothing))
sb.Append(",")
End If
Next
sb.Remove(sb.Length - 1, 1)
sb.Append(vbCrLf)
Next
Return sb.ToString()
End Function
Problematically, this includes all the navigation properties as columns. Is there an easy way to exclude the related objects? I had hoped that the check for virtual properties would do it:
If Not pi(index).GetAccessors()(0).IsVirtual Then...
but I think I am confusing this with EF.
Aucun commentaire:
Enregistrer un commentaire