DataTable转化成实体对象

时间:2024-10-14 11:03:32
     /// <summary>
/// The data extension.
/// </summary>
public static class DataExtension
{
/// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="reader">reader</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this IDataReader reader) where T : class, new()
{
var result = new List<T>(); DataTable dt = reader.GetSchemaTable();
try
{
while (reader.Read())
{
var t = new T(); if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
// 当前列名&属性名
string columnName = dr[].ToString();
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(reader[columnName], pro.PropertyType), null);
}
} result.Add(t);
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (!reader.IsClosed)
{
reader.Dispose();
reader.Close();
}
} return result;
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="dt">dt</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
var result = new List<T>();
foreach (DataRow dr in dt.Rows)
{
var t = new T();
try
{
foreach (DataColumn column in dt.Columns)
{
// 当前列名&属性名
string columnName = column.ColumnName;
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(dr[columnName], pro.PropertyType), null);
}
}
catch (System.Exception ex)
{
throw ex;
} result.Add(t);
} return result;
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataSet ds) where T : class, new()
{
return ds.Tables[].ToList<T>();
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <param name="dataTableIndex">dataTableIndex</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataSet ds, int dataTableIndex) where T : class, new()
{
return ds.Tables[dataTableIndex].ToList<T>();
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="reader">reader</param>
/// <returns>T</returns>
public static T ToModel<T>(this IDataReader reader) where T : class, new()
{
var t = new T();
DataTable dt = reader.GetSchemaTable();
try
{
while (reader.Read())
{
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
// 当前列名&属性名
string columnName = dr[].ToString();
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(reader[columnName], pro.PropertyType), null);
}
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (!reader.IsClosed)
{
reader.Dispose();
reader.Close();
}
} return t;
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="dt">dt</param>
/// <returns>T</returns>
public static T ToModel<T>(this DataTable dt) where T : class, new()
{
var t = new T();
if (dt.Rows.Count <= )
{
return t;
} try
{
foreach (DataColumn column in dt.Columns)
{
// 当前列名&属性名
string columnName = column.ColumnName;
PropertyInfo pro = typeof(T).GetProperty(columnName);
if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(dt.Rows[][columnName], pro.PropertyType), null);
}
}
catch (System.Exception ex)
{
throw ex;
} return t;
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <param name="dataTableIndex">dataTableIndex</param>
/// <returns>T</returns>
public static T ToModel<T>(this DataSet ds, int dataTableIndex = ) where T : class, new()
{
return ds.Tables[].ToModel<T>();
}
}

DataExtension

     /// <summary>
/// The convert extension.
/// </summary>
public static class ConvertExtension
{
/// <summary>
/// The convert helper.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <param name="conversionType">
/// The conversion type.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
public static object ConvertHelper(object value, Type conversionType)
{
Type nullableType = Nullable.GetUnderlyingType(conversionType); // 判断当前类型是否可为 null
if (nullableType != null)
{
if (value == DBNull.Value)
{
return null;
} // 若是枚举 则先转换为枚举
if (nullableType.IsEnum)
{
value = System.Enum.Parse(nullableType, value.ToString());
} return Convert.ChangeType(value, nullableType);
} if (conversionType.IsEnum)
{
return System.Enum.Parse(conversionType, value.ToString());
} return Convert.ChangeType(value, conversionType);
} /// <summary>
/// The convert to decimal null.
/// </summary>
/// <param name="targetObj">
/// The target obj.
/// </param>
/// <returns>
/// The <see cref="decimal"/>.
/// </returns>
public static decimal? ConvertToDecimalNull(object targetObj)
{
if (targetObj == null || targetObj == DBNull.Value)
{
return null;
} return Convert.ToDecimal(targetObj);
} /// <summary>
/// The convert to int null.
/// </summary>
/// <param name="targetObj">
/// The target obj.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public static int? ConvertToIntNull(object targetObj)
{
if (targetObj == null || targetObj == DBNull.Value)
{
return null;
} return Convert.ToInt32(targetObj);
} /// <summary>
/// The convert to string.
/// </summary>
/// <param name="obj">
/// The obj.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string ConvertToString(object obj)
{
return obj == null ? string.Empty : obj.ToString();
} /// <summary>
/// 将泛类型集合List类转换成DataTable
/// </summary>
/// <param name="entitys">泛类型集合</param>
/// <typeparam name="T">T</typeparam>
/// <returns>DataTable</returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
// 检查实体集合不能为空
if (entitys == null || entitys.Count < )
{
throw new System.Exception("需转换的集合为空");
} // 取出第一个实体的所有Propertie
Type entityType = entitys[].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties(); // 生成DataTable的structure
// 生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable();
foreach (PropertyInfo t in entityProperties)
{
// dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(t.Name);
} // 将所有entity添加到DataTable中
foreach (object entity in entitys)
{
// 检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new System.Exception("要转换的集合元素类型不一致");
} object[] entityValues = new object[entityProperties.Length];
for (int i = ; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
} dt.Rows.Add(entityValues);
} return dt;
} /// <summary>
/// 转换中文星期
/// </summary>
/// <param name="dt">The dt.</param>
/// <returns>Week.</returns>
public static Week ConverToWeekByZHCN(this DateTime dt)
{
return (Week)dt.DayOfWeek;
} /// <summary>
/// 四舍五入保留2位小数(中国式)
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static decimal DecimalTwoPlaces(this decimal d)
{
return Math.Round(d, , MidpointRounding.AwayFromZero);
}
}

ConvertExtension

将 IDataReader DataSet DataTable 转化成 List<T> Or T类型
上面是转化代码