在线求等大神解决Dataset转换成List问题

hfdianjing 2014-04-09 02:25:48
public class ConvertToList<T>
{
public static List<T> Convert(DataSet ds, int index)
{
List<T> list = new List<T>();
foreach (DataRow dr in ds.Tables[index].Rows)
{

list.Add((T)TsetValue(dr, typeof(T)));
}
return list;
}

private static Object TsetValue(DataRow dr, Type t)
{
Object obj = Assembly.GetAssembly(t).CreateInstance(t.FullName);

foreach (PropertyInfo info in obj.GetType().GetProperties())
{
if (info.PropertyType.FullName.StartsWith("System"))
{
if (dr.Table.Columns.Contains(info.Name))
{
info.SetValue(obj, dr[info.Name], null);
}
}
else
{
info.SetValue(obj, TsetValue(dr, info.PropertyType), null);
}
}
return obj;
}
调用List<Department> dplist = ConvertToList<Department>.Convert(DBHlper.ExecuteSearch(desql, null, CommandType.Text), 0);报错,因为CompanyCenter有个Company 的外键,没有处理过对象类型,求帮忙解决一下
...全文
368 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
exception92 2014-04-09
  • 打赏
  • 举报
回复

 public static List<T> EntityList<T>(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            List<T> list = new List<T>();
            T entity = default(T);
            foreach (DataRow dr in dt.Rows)
            {
                entity = Activator.CreateInstance<T>();
                PropertyInfo[] pis = entity.GetType().GetProperties();
                foreach (PropertyInfo pi in pis)
                {
                    if (dt.Columns.Contains(pi.Name))
                    {
                        if (!pi.CanWrite)
                        {
                            continue;
                        }
                        if (dr[pi.Name] != DBNull.Value)
                        {
                            Type t = pi.PropertyType;
                            if (t.FullName == "System.Guid")
                            {
                                pi.SetValue(entity, Guid.Parse(dr[pi.Name].ToString()), null);
                            }
                            else
                            {
                                pi.SetValue(entity, dr[pi.Name], null);
                            }
                        }
                    }
                }
                list.Add(entity);
            }
            return list;
        }

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧