i have code like this
public class People
{
public string name { get; set; }
}
public class Animal
{
public string age { get; set; }
}
class Test
{
public void DataPeopleList()
{
string sql = "SELECT * FROM People";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
List<People> list = new List<People>();
while (rdr.Read()) {
People p = new People();
p.name = rdr["name"].ToString();
list.Add(p);
}
rdr.Close();
}
public void DataAnimalList()
{
string sql = "SELECT * FROM Animal";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
List<People> list = new List<People>();
while (rdr.Read())
{
People p = new People();
p.name = rdr["age"].ToString();
list.Add(p);
}
rdr.Close();
}
}
i think is not good for me. can i write give class as parameter so when i want load data i just give query and class as parameter..example the code which i want like :
public void LoadData(string query, Type ClassName)
{
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader rdr = cmd.ExecuteReader();
List<ClassName> list = new List<ClassName>();
while (rdr.Read())
{
ClassName p = new ClassName();
//p.name = rdr["age"].ToString(); i dont have idea in this part
list.Add(p);
}
rdr.Close();
}
so I`m enough to call method like
public void DataAnimalList()
{
string sql = "SELECT * FROM Animal";
LoadData(sql,class Animal);
}
Can you give me an answer or hint..
Thanks in Advance
I feel, what you are thinking may not be that elegant solution. Because
1) You can use reflection but which can result in poor performance. So, better not to go for it until, it is badly needed.
2) Also, tomorrow, if the columns to deal with in the result set changes then anyway you need to go and tweak the code otherwise your code may fail.
So, better could be you can go for some ORM Framework as suggested by Ani.