首页 > 代码库 > DataSet转Model

DataSet转Model

  /// <summary>
    /// 返回List<Model>
    /// </summary>
    /// <typeparam name="T">Model类型</typeparam>
    /// <param name="entity">Model类型</param>
    /// <param name="ds"></param>
    /// <returns></returns>
    public static List<T> PutAll<T>(T entity, DataSet ds) where T : new()
    {
        try
        {
            List<T> lists = new List<T>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    lists.Add(Put(new T(), row));
                }
            }
            return lists;
        }
        catch (Exception)
        {
            //报错返回 null
            return null;
        }
    }


    /// <summary>
    /// 返回一条数据的Model
    /// </summary>
    /// <typeparam name="T">Model类型</typeparam>
    /// <param name="entity">Model类型</param>
    /// <param name="ds"></param>
    /// <returns></returns>
    public static T PutOne_Model<T>(T entity, DataSet ds) where T : new()
    {
        try
        {
            T m = new T();
            if (ds.Tables[0].Rows.Count > 0)
            {
                m = Put(new T(), ds.Tables[0].Rows[0]);
            }
            return m;
        }
        catch (Exception)
        {
            //报错返回 null
            return default(T);
            //throw;
        }
    }

    /// <summary>
    /// 处理数据行生成Model
    /// </summary>
    /// <typeparam name="T">Model类型</typeparam>
    /// <param name="entity">Model类型</param>
    /// <param name="row">数据行</param>
    /// <returns></returns>
    public static T Put<T>(T entity, DataRow row) where T : new()
    {
        //初始化 如果为null
        if (entity == null)
        {
            entity = new T();
        }
        //得到类型
        Type type = typeof(T);
        //取得属性集合
        PropertyInfo[] pi = type.GetProperties();
        foreach (PropertyInfo item in pi)
        {
            //判断数据中是否包含此列
            int index = row.Table.Columns.IndexOf(item.Name);
            if (index != -1)
            {
                //给属性赋值
                if (row[item.Name] != null && row[item.Name] != DBNull.Value)
                {
                    if (item.PropertyType == typeof(System.DateTime))
                    {
                        //如果对日期格式有特殊要求 可以在这里转换
                        //日期要为空值 定义Model DateTime? 即可
                        item.SetValue(entity, Convert.ToDateTime(row[item.Name].ToString()), null);
                    }
                    else
                    {
                        //按Model原数据类型转换
                        item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
                    }
                }
            }
        }
        return entity;
    }

 

DataSet转Model