I have a scenario to query DB for two columns and return all the rows to a different method for further processing. I am not sure if my approach below is the best. Can you please share any better techniques to accomplish this. The below code works well for a single row returned from SQL.
public (Int32 SiteID, string SiteName) QueryDB(string ConnStr)
{
Int32 SiteID = 0;
string SiteName = "";
using (SqlConnection con = new SqlConnection(ConnStr))
{
SqlCommand cmd = new SqlCommand("spGetSiteDetails", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
SiteID = Convert.ToInt32(reader[0]);
SiteName = reader[1].ToString();
}
}
return (SiteID, SiteName);
}
In order to address multiple rows result, I am using string concatenated in a List. I believe there must be a better way of doing this because I have an overhead of having to split the string in the list to use the values..
public List<string> QueryDB(string ConnStr)
{
List<string> SiteDetails = new List<string>();
using (SqlConnection con = new SqlConnection(ConnStr))
{
SqlCommand cmd = new SqlCommand("spGetSiteDetails", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
SiteDetails.Add(reader[0] + "|" + reader[1]);
}
}
return SiteDetails;
}
List<object>and add column values to it instead of appending strings. Use an ORM to automagically convert rows to objects, or a microORM like Dapper to do the same with a single line.reader[0]orreader[1]is unique you can store as dictionaryreader.GetValues()to fill an array with all values in a single operationSiteId and SiteNameinstead of two separate variables?