Providing type in generic argument when using Dapper QueryMultiple

c# dapper generics runtime

Question

I'm trying to create a layer over dapper and want to create a method that uses the QueryMultiple method. I want to map an incoming list of types in string format (determined at runtime) with the QueryMultiple's Read method. When trying to use the Read method I can't find a way to make the generic argument accept the type i'm creating.

Can anyone please help me on how to correctly provide the type?

Here's the code:

using (SqlConnection conn = GetNewConnection())
{
    conn.Open();
    var multi = conn.QueryMultiple(sql, param);
    foreach (string typeName in ListOfTypes)  //Iterate a List of types in string format.
    {
        Type elementType=  Type.GetType(typeName);
        var res= multi.Read<elementType>();  //Error: The type or namespace name 'combinedType' could not be found (are you missing a using directive or an assembly reference?)
        //Add result to a dictionary
    }
}

Accepted Answer

The QueryMultiple.Read<T>() method currently being used takes a generic type parameter which must be known at compile time. In other words, elementType cannot be used as a generic type parameter within the <T> parameter:

Type elementType = Type.GetType(typeName);
var res = multi.Read<elementType>(); // /Error: The type or namespace... etc.

If the type is not know until runtime, use the QueryMultiple.Read(Type type) method:

Type elementType = Type.GetType(typeName);
var res = multi.Read(elementType); 

See MSDN for more info on Generic Type Parameters.




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