【CSharp】Model转换工具类
本文最后更新于 2024-05-07,文章可能存在过时内容,如有过时内容欢迎留言或者联系我进行反馈。
代码示例
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;
}
/// <summary> 将Table中的一行数据转换成实体 </summary>
/// <param name="dr"> Table中的一行数据 </param>
/// <returns> </returns>
public static T FillSigleMode(DataRow dr)
{
T model = new T();
if (dr != null)
{
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);
}
}
return model;
}
/// <summary> 实体类转换成DataTable </summary>
/// <param name="modelList"> 实体类列表 </param>
/// <returns> </returns>
public static DataTable FillDataTable(List<T> 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;
}
/// <summary> 根据实体类得到表结构 </summary>
/// <param name="model"> 实体类 </param>
/// <returns> </returns>
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;
}
}
}
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果