简体   繁体   English

使用泛型的Dapper方法

[英]Dapper Method using generics

I am trying to create a common dapper 'read' method.I am wanting to pass the return type in as a parameter to the method.I am unfamiliar with generics but have an idea that it could be done using generics. 我正在尝试创建一个通用的dapper'read'方法,我想将返回类型作为参数传递给该方法,我不熟悉泛型,但是有一个想法可以使用泛型来完成。 I'm thinking it will look something like this? 我在想看起来会是这样吗?

public static T ListReader<T>(string SQL, ref T returnType, string DbName = "TEST")
{
    using (IDbConnection cmd = new SqlConnection(ConfigurationManager.ConnectionStrings[DbName].ConnectionString))
    {
        return cmd.Query<returnType>(SQL).ToList();
    }
}

You're mixing generics, which must be known at compile-time, with objects. 您正在将泛型(必须在编译时知道)与对象混合在一起。

Remove that returnType that doesn't add anything useful and fix the return type: 删除不会添加任何有用内容的returnType并修复返回类型:

public static IEnumerable<T> ListReader<T>(string SQL, string DbName = "TEST")
{
    using (IDbConnection cmd = new SqlConnection(ConfigurationManager.ConnectionStrings[DbName].ConnectionString))
    {
        return cmd.Query<T>(SQL).ToList();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM