Skip to content

How to list aliased columns on reader

Guest User

Asked May 19, 2016, 8:20 AM EDT1 answer
Share
LinkedInX
I'm trying to populate a chart and I need to grab data from an SQL Server database, I got my query and its quite simple but is made out of functions so the columns are all aliased, so when I try to add the columns to the reader I get no results, it just wont find them.
 
Here's my sample code...
 
 
  1. public static List<Work> ListNaturalResources(int directorateId)  
  2. {  
  3.     var newList = new List<CasesWorkType>();  
  4.   
  5.     using (var connection = new SqlConnection(Settings.Default.ServicesConnectionString))  
  6.     {  
  7.         connection.Open();  
  8.         string sql = "SELECT " +  
  9.                      "MONTH(DateCreated) AS dMonth," +  
  10.                      "YEAR(DateCreated) AS dYear," +  
  11.                      "COUNT(*) AS dCount" +  
  12.                      "FROM Works" +  
  13.                      "WHERE DirectorateID = " + directorateId + " " +  
  14.                      "GROUP BY " +  
  15.                      "MONTH(DateCreated), " +  
  16.                      "YEAR(DateCreated);";  
  17.   
  18.         using (var command = new SqlCommand(sql, connection))  
  19.         {  
  20.             using (var reader = command.ExecuteReader())  
  21.             {  
  22.                 while (reader.Read())  
  23.                 {  
  24.                     var countPerDirectorate = new Work();  
  25.                     countPerDirectorate. ??????  =  reader["WorkDescription"].ToString();     
  26.                     newList.Add(countPerDirectorate);  
  27.                 }  
  28.             }  
  29.         }  
  30.     }  
  31.     return newList;  
  32. }  

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    BUZZZ!!!
    I got it, create a new class
    1. public partial class WorksPerDirectorate
    2. {
    3. public int DMonth {get;set;}
    4. public int DYear {get;set;}
    5. public int DCount {get;set;}
    6. }
    and then:
    1. using(var reader = command.ExecuteReader())
    2. {
    3. while(reader.Read())
    4. {
    5. var nw = new WorksPerDirectorate();
    6. nw.DMonth = (int)reader["dMonth"];
    7. nw.DYear = (int)reader["dYear"];
    8. nw.DCount = (int)reader["dCount"];
    9. newList.Add(nw);
    10. }
    11. }
    Sorry, I just rushed into asking...
    0