51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

【CSharp】Model转换工具类

本文最后更新于 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;
    }

    /// <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;
    }
}

}



赞(2)
未经允许不得转载:工具盒子 » 【CSharp】Model转换工具类