If make a query from database,we need to use DataSet at first to fill the result,then write funtion like Row2XXX to convert it to a data struct.It will be a crazy job when you query many tables in database.Now I write a function to reflect it automatically,it can put all the data in a table to a list of data class accordingly.
using System.Reflection; public static ListGetList (string table) where T : new() { string sql = "select * from " + table; DataSet ds = SQLiteHelper.ExecuteQuery(sql); if (ds == null) return null; List list = new List (); PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); foreach (DataRow row in ds.Tables[0].Rows) { T t = new T(); foreach (PropertyInfo property in properties) { object value = row[property.Name]; if (value != DBNull.Value) property.SetValue(t, value, null); } list.Add(t); } return list; }
Define modal class,the name of the property has to be same as the name of column in database,the call the function
public class TestItem
{
private string s;
public string S
{
get { return s; }
set { s = value; }
}
}
List list = GetList("tablename");
No related posts.
