使用Dapper QueryMultiple时提供泛型参数的类型

时间:2015-07-03 20:37:10

标签: c# generics runtime dapper

我试图在dapper上创建一个图层,并希望创建一个使用QueryMultiple方法的方法。我想用字符串格式(在运行时确定)映射一个类型的传入列表与QueryMultiple的Read方法。当我尝试使用Read方法时,我无法找到一种方法来使泛型参数接受i' m创建的类型。

有谁可以帮我解释如何正确提供类型?

以下是代码:

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

1 个答案:

答案 0 :(得分:2)

当前使用的QueryMultiple.Read<T>()方法采用泛型类型参数,必须在编译时知道。换句话说,elementType不能用作<T>参数中的泛型类型参数:

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

如果直到运行时才知道类型,请使用QueryMultiple.Read(Type type)方法:

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

有关Generic Type Parameters的详细信息,请参阅MSDN。