Generic Argument Type Providing When Using Dapper QueryMultiple

I am trying to create a layer on top of dapper and want to create a method that uses the QueryMultiple method. I want to match an incoming list of types in string format (defined at runtime) using the QueryMultiple Read method. When trying to use the Read method, I can't seem to find a way to make the generic argument acceptable to the type I'm creating.

Can anyone help me on how to specify the type correctly?

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
    }
}

      

+3


source to share


1 answer


The currently used method QueryMultiple.Read<T>()

takes a generic type parameter, which must be known at compile time. In other words, elementType

it cannot be used as a type parameter in a parameter <T>

:

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

      

If the type is unknown prior to execution, use the method QueryMultiple.Read(Type type)

:



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

      

See MSDN for more information on Type Parameters .

+2


source







All Articles