Exemplo n.º 1
0
        /// <summary>
        /// 把DataRow转成实体对象。
        /// </summary>
        /// <param name="dr">DataRow。</param>
        /// <param name="type">实体类型。</param>
        /// <returns>实体对象。</returns>
        public object ConvertFromDataRowToEntity(DataRow dr, Type type)
        {
            object result = Activator.CreateInstance(type);

            foreach (var propertyInfo in type.GetProperties())
            {
                if (dr.Table.Columns.Contains(propertyInfo.Name))
                {
                    propertyInfo.SetValue(result, TypeConvert.Convert(dr[propertyInfo.Name], propertyInfo.PropertyType), null);
                }
            }
            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 把DataTable转成实体集合。
        /// </summary>
        /// <typeparam name="T">实体类型。</typeparam>
        /// <param name="dt">DataTable。</param>
        /// <returns>实体集合。</returns>
        public List <T> ConvertFromDataTableToEntities <T>(DataTable dt)
        {
            List <T> result = new List <T>();

            foreach (DataRow dr in dt.Rows)
            {
                Type itemType = typeof(T);
                T    t        = (T)Activator.CreateInstance(itemType);
                foreach (var propertyInfo in itemType.GetProperties())
                {
                    string columnName = propertyInfo.Name;
                    if (dt.Columns.Contains(columnName))
                    {
                        propertyInfo.SetValue(t, TypeConvert.Convert(dr[columnName], propertyInfo.PropertyType), null);
                    }
                }
                result.Add(t);
            }
            return(result);
        }