Cast Class Type at Runtime in VB.NET

.net casting dapper runtime


I have looked at dozens of answers, and three of them seem really close to what I'm trying to achieve.

I have a database with hundreds of views. I use dapper to query the results of a view. I present the results in a grid. This is a read-only operation. The view results are already mapped to classes. Here is a typical query:

queryResults = conn.Query(Of vw_EmployeeProductDetails)(queryString, Nothing)

Right now, I have a separate query for each view (each in its own function). I would prefer to pass in the queryString and a "ViewType" to a single function to get results.

'pass Type as function parameter
Dim ViewType = GetType(vw_EmployeeProductDetails)
SelectView(queryString, ViewType)


'in the generic query function:
queryResults = conn.Query(Of ViewType)(queryString, Nothing)

However, this will not compile and I receive the error "Type 'ViewType' is not defined."

I have tried creating an instance of the specific class, then passing that type. I have used Activator.CreateInstance in multiple configurations. I tried using MakeGenericType. I tried explicitly putting the results in a list of "ViewType":

Dim ViewType = GetType(List(Of )).MakeGenericType(GetType(vw_EmployeeProductDetails))
Dim list = Activator.CreateInstance(ViewType)
list = conn.Query(queryString, Nothing)

None of the above (along with more dead-ends) worked. The code above got me back to square one (a generic object that can't easily be shown in a grid, even though the correct properties are all there, without throwing it back in a dataset/datatable).

I am reading more about generic types to see if I can get the compiler to recognize the Type in Query(Of ViewType), but I still cannot quite grasp how to put it all together or if that approach would work (e.g. would all my ViewTypes inherit from the generic class?).

This code won't compile for the same reason:

Dim ViewType= GetType(List(Of )).MakeGenericType(GetType(vw_EmployeeProductDetails))
Dim list = Activator.CreateInstance(ViewType)
Dim list2() As List(Of ViewType)

When creating list2, ViewType is not defined. I'm absolutely lost on how to define it, if it is even possible, or if I should scrap the entire approach.

Can anyone offer insight on if this is possible? If so, how can I implement it. If not, is there a suitable alternative in this situation?

Accepted Answer

Your generic query function should accept a generic type parameter:

 Public Function MyQueryFunction(Of T)(queryString As String) As List(Of T)
    return conn.Query(Of T)(queryString, Nothing)
 End Function

And you would call it like this:

  Dim myresults as List(Of vw_EmployeeProductDetails) = MyQueryFunction(Of vw_EmployeeProductDetails)(queryString)

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why