DataTable转换成实体

时间:2023-03-09 17:07:42
DataTable转换成实体
public static class DataTableToEntity
{
/// <summary>
/// 将DataTable数据源转换成实体类
/// </summary>
public static List<T> ConvertToModel<T>(this DataTable dt) where T : new()
{
List<T> ts = new List<T>();// 定义集合
foreach (DataRow dr in dt.Rows)
{
T t = new T();
PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
foreach (PropertyInfo pi in propertys)
{
if (dt.Columns.Contains(pi.Name))
{
if (!pi.CanWrite) continue;
var value = dr[pi.Name];
try
{
if (value != DBNull.Value && value != null && value.ToString() != "")
{
if (pi.PropertyType.FullName.ToUpper().Contains("DECIMAL"))
{
pi.SetValue(t, decimal.Parse(value.ToString()), null);
}
else if (pi.PropertyType.FullName.ToUpper().Contains("DOUBLE"))
{
pi.SetValue(t, double.Parse(value.ToString()), null);
}
else if (pi.PropertyType.FullName.ToUpper().Contains("INT32"))
{
pi.SetValue(t, int.Parse(value.ToString()), null);
}
else if (pi.PropertyType.FullName.ToUpper().Contains("INT16"))
{
pi.SetValue(t, short.Parse(value.ToString()), null);
}
else
pi.SetValue(t, value, null); }
}
catch (Exception ex)
{
//throw ex;
} }
}
ts.Add(t);
}
return ts;
}
}
//直接调用
DataTable dt = new DataTable();
List<实体类> testList = dt.ConvertToModel<实体类>();
//或者调用 获取转换为实体数据后指定条件的数据
DataTable dt = new DataTable();
foreach (DataRow row in dt.Rows)
{
List<实体类> testList = dt.ConvertToModel<实体类>();
实体类 tempEntity = testList.Where(t => t.字段== row1["字段"].ToString()).FirstOrDefault();
}