简体   繁体   中英

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. 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:

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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