首页 > 其他 > 详细

DataRow映射实体

时间:2015-03-20 12:29:43      阅读:362      评论:0      收藏:0      [点我收藏+]
 public static T ConvertToModel<T>(DataRow dr) where T : new()
        {
            T t = new T();
            Type modelType = t.GetType();
            foreach (PropertyInfo pi in modelType.GetProperties())
            {
                if (pi == null) continue;
                if (pi.CanWrite == false) continue;

                if (dr.Table.Columns.Contains(pi.Name))
                {
                    //p.SetValue(t, GetDefaultValue(dr[p.Name], p.PropertyType), null);
                    try
                    {
                        if (dr[pi.Name] != DBNull.Value)
                            pi.SetValue(t, dr[pi.Name], null);
                        else
                            pi.SetValue(t, default(object), null);
                    }
                    catch
                    {
                        pi.SetValue(t, GetDefaultValue(dr[pi.Name], pi.PropertyType), null);
                    }
                }

            }
            return t;
        }

        private static object GetDefaultValue(object obj, Type type)
        {
            if (obj == DBNull.Value)
            {
                return default(object);
            }
            else
            {
                return Convert.ChangeType(obj, type);
            }
        }

  纯代码难得打字

DataRow映射实体

原文:http://www.cnblogs.com/gclearn/p/4353012.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!