Home > Back-end >  Dapper: Using <T> to execute multiple queries from different resources
Dapper: Using <T> to execute multiple queries from different resources

Time:10-22

Ok so I have ZERO idea how to word it in a title so I will explain what I am looking to achieve here.

I have a .cs file that houses a connection code utilizing dapper listed below.

namespace DBConnector
{

    public static class Helper
    {

        public static string CnnVal(string name)
        {
            return ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }

    }

    public class DataAccess<T>
    {
        public List<T> GetInfo(string query, object parameters = null)
        {
            using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("ProxyRPDB")))
            {
                return connection.Query<T>(string, object);
            }
        }
    }
}

What I am trying to achieve, is have a query executed from a DIFFERENT .cs file through the above code. BUT! I am trying to make it so that above code accepts query executions from multiple .cs files that all need different data from different tables. I have tried forever to find the information... so this is truly last resort. I am using Dapper for .NET 4.5.2.

CodePudding user response:

First, we need to fix the basic syntax errors in the GetInfo() method:

public static class DataAccess
{
    public static IEnumerable<T> GetInfo<T>(string query, object parameters = null)
    {
        using (var connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("ProxyRPDB")))
        {
            return connection.Query<T>(query, parameters);
        }
    }
}

Now, assuming you have the proper reference and using directives in other *.cs files, you can do things like this inside those files:

var results = DataAccess.GetInfo<MyTableType>("SELECT * FROM [MyTable]");
foreach(var record in results)
{
  //...
}

Dapper will now try to map the query results to instances of the MyTableType class, so make sure you've created such a class.

Note this works with IEnumerable instead of List. If you really need a List (hint: you usually don't, and IEnumerable can perform much better) you can always put a .ToList() at the end of the function call:

var results = DataAccess.GetInfo<MyTableType>("SELECT * FROM [MyTable]").ToList();
  • Related