据数据库的表字段为实体类相同名称属性赋值


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
public class DataBaseUntity
    {
        //获取数据库数据:据数据库的表字段为实体类相同名称属性赋值
        public static IList SetEntityFromDB(DataTable dt)
        {
            IList list = new List();
            Type type = typeof(T);
            System.Reflection.PropertyInfo[] properties = type.GetProperties();
            foreach (DataRow dr in dt.Rows)
            {
                T t = Activator.CreateInstance();  
                for (int i = 0; i < properties.Length; i++)
                {
                    if (dt.Columns.Contains(properties[i].Name))
                    {
                        properties[i].SetValue(t, dr[properties[i].Name], null);
                    }
                }
                list.Add(t);
            }

            return list;
        }

        //向数据库传参:据实体构造参数
        public static ArrayList GetParamsFromEntity(T t) {
            Type type = typeof(T);
                      
            System.Reflection.PropertyInfo[] properties = type.GetProperties();
            //SqlParameter[] sps = new SqlParameter[properties.Length-1];
            ArrayList args = new ArrayList();
            SqlParameter sp;
            for (int i = 0; i < properties.Length; i++) {
                args.Add(new SqlParameter(string.Format("@{0}",properties[i].Name),properties[i].GetValue(t,null)));
            }

            return args;
        }

    }