【C#】DataTable转换为实体集

363 阅读1分钟

Model字段名称必须与数据库字段名称相同

private List<T> TableToList<T>(DataTable dt) where T : class, new()
{
    Type type = typeof(T);
    List<T> list = new List<T>();

    foreach (DataRow row in dt.Rows)
    {
        PropertyInfo[] properties = type.GetProperties();
        T model = new T();
        foreach (PropertyInfo p in properties)
        {
            object value = row[p.Name];
            if (value == DBNull.Value)
            {
                p.SetValue(model, "", null);
            }
            else
            {
                if (value is decimal)
                {
                    p.SetValue(model, Convert.ToInt32(value), null);
                }
                else
                {
                    p.SetValue(model, value, null);
                }
            }
        }
        list.Add(model);
    }
    return list;
}

使用

string sql = "select * from student";

DataTable dt = SqlHelper.ExecuteDataTable(sql);

List<Student> list = TableToList<Student>(dt);