Search code examples
c#ado.net

Refactor SqlDataReader neat api for doing database queries


I am trying to refactor this shared sqlDataReader into a neat api for doing database queries? I convert the dictionary to sql parameters. Run the query and get the reader and then convert the rows to items. How can I convert this SqlParameter into a Dictionary<string, object> and then into a SqlParameter ?

public class Program
{
    public static void Main()
    {
            DB("Test");
        
    }
    
    public DB(string templateTitle){
        string queryName = "usp_Select_ByTitle";
            
        var parameters = new Dictionary<string, object>()
        {
                ["TemplateTitle"] = templateTitle
        };
        
        RunStoredProcedure(queryName, parameters, (reader) => {
            return new DB(reader);
        });
    }
    
    public DB(int? titleId, int? bookId){
        string queryName = "usp_Select_Byids";
            
        var parameters = new Dictionary<string, object>()
        {
                ["titleId"] = titleId,
                ["bookId"] = bookId,
        };
        
        RunStoredProcedure(queryName, parameters, (reader) => {
            return new DB(reader);
        });
    }
    
     public List<CompendiaNewDB> RunStoredProcedure(string queryName, IDictionary<string, object> parameters, Func<SqlDataReader> reader){
         var spParameters = new SqlParameter();
         string ConnectionString = "";
         string SQL = queryName;
         foreach (KeyValuePair<String, Object> p in parameters)
         {
                new SqlParameter("@" + p.Key, (p.Value.ToString().Length == 0) ? DBNull.Value : p.Value);
         }
         
         SqlConnection conn = new SqlConnection(ConnectionString);

         SqlCommand cmd = new SqlCommand(SQL, conn);
         conn.Open();

         SqlDataReader reader = cmd.ExecuteReader();

         while (reader.Read())
         {

         }
         
     }

Solution

  • Welcome to Dapper, which exists literally to do this and only this:

    
    public List<CompendiaNewDB> GetBooks(int? titleId, int? bookId)
    {
        return connection.Query<CompendiaNewDB>(
            "usp_Select_Byids",
            new { titleId, bookId }, // named parameters/args
            commandType: CommandType.StoredProcedure
        ).AsList();
    }
    

    The library will know more about using ADO.NET correctly than most casual users will, and is pretty reliable and trusted.