就是方便了操作,更直观的反映获得的实体
直接上代码
public static class DataTableToEntityExtension { public static List<T> ToEntityList<T>(this DataTable dt) where T : class,new() { if (dt == null || dt.Rows.Count == 0) return new List<T>(); List<T> entityList = new List<T>(); Type entityType = typeof(T); PropertyInfo[] propertys = entityType.GetProperties(); DataMappingAttribute mappingAttribute = null; object value = null; foreach (DataRow dr in dt.Rows) { T tEntity = new T(); foreach (PropertyInfo pi in propertys) { if (!pi.CanWrite) continue; //pi. var mattr = pi.GetCustomAttributes(typeof(DataMappingAttribute), false); //mappingAttribute = (DataMappingAttribute)pi.GetCustomAttributes(false)[0]; if (mattr.Count() > 0) { mappingAttribute = mattr[0] as DataMappingAttribute; } if (mappingAttribute == null) { if (dt.Columns.Contains(pi.Name)) { value = dr[pi.Name]; } else { if (pi.PropertyType == typeof(decimal) || pi.PropertyType == typeof(int) || pi.PropertyType == typeof(double) || pi.PropertyType == typeof(float)) { value = 0; } else { value = null; } } } else if (mappingAttribute != null && dt.Columns.Contains(mappingAttribute.mappingName)) { value = dr[mappingAttribute.mappingName]; } if (value != DBNull.Value) { pi.SetValue(tEntity, value, null); } } entityList.Add(tEntity); } return entityList; } public static T ToEntity<T>(this DataTable dt) where T : class,new() { if (dt == null || dt.Rows.Count == 0) return new T(); Type entityType = typeof(T); PropertyInfo[] propertys = entityType.GetProperties(); DataMappingAttribute mappingAttribute = null; object value = null; DataRow dr = dt.Rows[0]; T tEntity = new T(); foreach (PropertyInfo pi in propertys) { if (!pi.CanWrite) continue; //pi. var mattr = pi.GetCustomAttributes(typeof(DataMappingAttribute), false); //mappingAttribute = (DataMappingAttribute)pi.GetCustomAttributes(false)[0]; if (mattr.Count() > 0) { mappingAttribute = mattr[0] as DataMappingAttribute; } if (mappingAttribute == null) { if (dt.Columns.Contains(pi.Name)) { value = dr[pi.Name]; } else { if (pi.PropertyType == typeof(decimal) || pi.PropertyType == typeof(int) || pi.PropertyType == typeof(double) || pi.PropertyType == typeof(float)) { value = 0; } else { value = null; } } } else if (mappingAttribute != null && dt.Columns.Contains(mappingAttribute.mappingName)) { value = dr[mappingAttribute.mappingName]; } if (value != DBNull.Value) { pi.SetValue(tEntity, value, null); } } return tEntity; } } [AttributeUsage(AttributeTargets.Property)] public class DataMappingAttribute : Attribute { public string mappingName; public DbType dbType; public DataMappingAttribute() { } public DataMappingAttribute(string mappingName, DbType dbType) { this.mappingName = mappingName; this.dbType = dbType; } }
使用:
List<UserInfo> userList = dataTable.ToEntityList<UserInfo>(); UserInfo user = dataTable.ToEntity<UserInfo>();
微信扫码查看本文
发表评论