I know this is a simple question for you. But I am a beginner in c#.
What I want to achieve is to create a method that will store any type of List of Objects from my Model. e.g List<Person>
.
I have tried to make something like this..
public IEnumerable<T> GetObjects<T>()
{
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo item in properties)
{
// store properties
}
List<T> objects = new List<T>();
using (SqlConnection str = GetSqlConnection)
{
// retrieve data from db
//then store it to list of objects
}
return objects;
}
This will enable me to retrieve data using only this method.
EDIT:
I already manage to create this sample code to retrieve a specific table from a database.
public IEnumerable<ItemBrand> getAllBrand
{
get
{
List<ItemBrand> brands = new List<ItemBrand>();
using (MySqlConnection strConn = getMySqlConnection())
{
string query = "SELECT * FROM tblbrand";
MySqlCommand cmd = new MySqlCommand(query, strConn);
strConn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
ItemBrand brand = new ItemBrand();
brand.brandID = Convert.ToInt32(rd["brandID"]);
brand.Name = rd["brandName"].ToString();
brands.Add(brand);
}
return brands;
}
}
}
Currently I have multiple methods of this in my solution. I would love to remove those duplicate codes with your help.
I have written a method that gets the result retrieved from a stored proc and transformes it into a list of objects. The only thing you need to pay attention to is: The class you are mapping to must have the same column names as the ones that are sent from the database.