jeudi 1 juin 2017

How to use attribute and reflection to retrieve data from sql database using asp.net?

Normally I would use data reader with column index to retrieve data from database but now, i wanted to integrate attribute and use reflection so that i can just loop the properties, as opposed to updating every single connection whenever there are changes on the database. I also thought about using ORM but i just wanted to learn how to use attributes and reflection in this type of scenario.

Originally I have a class that would set the data from SQL with properties like this:

public class TShirt
{   
public int Id { get; set; }
public string Type { get; set; }
public string Brand { get; set; }

public TShirt()
{

}
public TShirt(int id, string type, string brand)
{
    Id = id;
    Type = type;
    Brand = brand;
}

And i would connect to the database through this code:

public static ArrayList GetTShirt(string itemCategory)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM shirt WHERE brand LIKE @brand");

try
{
    conn1.Open();
    command1.CommandText = query;
    command1.Parameters.Add(new SqlParameter("brand", itemCategory));
    SqlDataReader reader = command1.ExecuteReader();

    while (reader.Read())
    {
        int id = reader.GetInt32(0);
        string type = reader.GetString(1);
        string brand = reader.GetString(2);

        TShirt t = new TShirt(id, type, brand);
        list.Add(t);
    }
}
finally
{
    conn1.Close();
    command1.Parameters.Clear();
}

return list;
}

How would you transform this code to integrate attribute and reflection? I've really tried to search online for answers but none of it helps. I also attempted to modify the GetTShirt Method but i just don't have any knowledge about this to base on.





Aucun commentaire:

Enregistrer un commentaire