本文最后更新于 2024-05-07,文章可能存在过时内容,如有过时内容欢迎留言或者联系我进行反馈。
代码示例 {#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B}
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ToolClass
{
/// <summary> ModelUtil 实体转换工具类 </summary>
public class ModelUtil<T> where T : new()
{
/// <summary> Table转换成实体 </summary>
/// <param name="dt"> 表 </param>
/// <returns> </returns>
public static List<T> FillModel(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
List<T> modelList = new List<T>();
foreach (DataRow dr in dt.Rows)
{
//T model = (T)Activator.CreateInstance(typeof(T));
T model = new T();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (propertyInfo != null && dr[i] != DBNull.Value)
propertyInfo.SetValue(model, dr[i], null);
}
modelList.Add(model);
}
return modelList;
}
/// &lt;summary&gt; 将Table中的一行数据转换成实体 &lt;/summary&gt;
/// &lt;param name="dr"&gt; Table中的一行数据 &lt;/param&gt;
/// &lt;returns&gt; &lt;/returns&gt;
public static T FillSigleMode(DataRow dr)
{
T model = new T();
if (dr != null)
{
for (int i = 0; i &lt; dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (propertyInfo != null &amp;&amp; dr[i] != DBNull.Value)
propertyInfo.SetValue(model, dr[i], null);
}
}
return model;
}
/// &lt;summary&gt; 实体类转换成DataTable &lt;/summary&gt;
/// &lt;param name="modelList"&gt; 实体类列表 &lt;/param&gt;
/// &lt;returns&gt; &lt;/returns&gt;
public static DataTable FillDataTable(List&lt;T&gt; modelList)
{
if (modelList == null || modelList.Count == 0)
{
return null;
}
DataTable dt = CreateData(modelList[0]);
foreach (T model in modelList)
{
DataRow dataRow = dt.NewRow();
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
}
dt.Rows.Add(dataRow);
}
return dt;
}
/// &lt;summary&gt; 根据实体类得到表结构 &lt;/summary&gt;
/// &lt;param name="model"&gt; 实体类 &lt;/param&gt;
/// &lt;returns&gt; &lt;/returns&gt;
private static DataTable CreateData(T model)
{
DataTable dataTable = new DataTable(typeof(T).Name);
foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
{
dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
}
return dataTable;
}
}
}