datatable转换为list<model> 映射

本文介绍了一种实用的数据映射方法,通过C#代码实现,能够将数据读取器(IDataReader)或数据表(DataTable)中的数据快速映射到自定义模型类中。这种方法特别适用于ORM框架中数据层与业务层之间的数据转换。
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;

namespace PORM.Data
{
    /// <summary>
    /// 常用映射关系帮助类
    /// </summary>
    public class CommonMap
    {
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dReader"></param>
        /// <returns></returns>
        public static IEnumerable<T> MapToIEnumerable<T>(IDataReader dReader) where T : class
        {
            using (dReader)
            {
                List<string> drFields = new List<string>(dReader.FieldCount);
                for (int i = 0; i < dReader.FieldCount; i++)
                {
                    drFields.Add(dReader.GetName(i).ToLower());
                }
                while (dReader.Read())
                {
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (drFields.Contains(pi.Name.ToLower()))
                        {
                            if (pi.PropertyType.IsEnum)
                            {
                                object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                                pi.SetValue(model, enumName, null);
                            }
                            else
                            {
                                if (!IsNullOrEmptyOrDBNull(dReader[pi.Name]))
                                {
                                    pi.SetValue(model, MapNullableType(dReader[pi.Name], pi.PropertyType), null);
                                }
                            }
                        }
                    }
                    yield return model;
                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static IEnumerable<T> MapToIEnumerable<T>(DataTable table) where T : class
        {
            foreach (DataRow row in table.Rows)
            {
                yield return MapToModel<T>(row);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dReader"></param>
        /// <returns></returns>
        public static T MapToModel<T>(IDataReader dReader) where T : class
        {
            using (dReader)
            {
                if (dReader.Read())
                {
                    List<string> drFields = new List<string>(dReader.FieldCount);
                    for (int i = 0; i < dReader.FieldCount; i++)
                    {
                        drFields.Add(dReader.GetName(i).ToLower());
                    }
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (drFields.Contains(pi.Name.ToLower()))
                        {
                            if (pi.PropertyType.IsEnum)
                            {
                                object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                                pi.SetValue(model, enumName, null);
                            }
                            else
                            {
                                if (!IsNullOrEmptyOrDBNull(dReader[pi.Name]))
                                {
                                    pi.SetValue(model, MapNullableType(dReader[pi.Name], pi.PropertyType), null);
                                }
                            }
                        }
                    }
                    return model;
                }
            }
            return default(T);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dRow"></param>
        /// <returns></returns>
        public static T MapToModel<T>(DataRow dRow) where T : class
        {
            try
            {
                List<string> drItems = new List<string>(dRow.ItemArray.Length);
                for (int i = 0; i < dRow.ItemArray.Length; i++)
                {
                    drItems.Add(dRow.Table.Columns[i].ColumnName.ToLower());
                }
                T model = Activator.CreateInstance<T>();
                foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                {
                    if (drItems.Contains(pi.Name.ToLower()))
                    {
                        if (pi.PropertyType.IsEnum) //属性类型是否表示枚举
                        {
                            object enumName = Enum.ToObject(pi.PropertyType, pi.GetValue(model, null));
                            pi.SetValue(model, enumName, null); //获取枚举值,设置属性值
                        }
                        else
                        {
                            if (!IsNullOrEmptyOrDBNull(dRow[pi.Name]))
                            {
                                pi.SetValue(model, MapNullableType(dRow[pi.Name], pi.PropertyType), null);
                            }
                        }
                    }
                }
                return model;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <param name="mType"></param>
        /// <returns></returns>
        public static object MapNullableType(object value, Type mType)
        {
            if (mType.IsGenericType && mType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (IsNullOrEmptyOrDBNull(value))
                    return null;
                System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(mType);
                mType = nullableConverter.UnderlyingType;
            }
            if (mType == typeof(bool) || mType == typeof(Boolean))
            {
                if (value is string)
                {
                    if (value.ToString() == "1")
                        return true;
                    else
                        return false;
                }
            }
            if (mType.IsEnum) //属性类型是否表示枚举
            {
                int intvalue;
                if (int.TryParse(value.ToString(), out intvalue))
                    return Enum.ToObject(mType, Convert.ToInt32(value));
                else
                    return System.Enum.Parse(mType, value.ToString(), false);
            }
            return Convert.ChangeType(value, mType);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T MapType<T>(object value)
        {
            Type type = typeof(T);
            if (CommonMap.IsNullOrEmptyOrDBNull(value))
                value = type.IsValueType ? Activator.CreateInstance(type) : null;
            if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                try
                {
                    return (T)Convert.ChangeType(value, type.GetGenericArguments()[0]);
                }
                catch
                {
                    value = null;
                    return (T)value;
                }
            }
            if (type.IsEnum)
                return (T)Enum.ToObject(type, value);
            return (T)Convert.ChangeType(value, typeof(T));
        }

        /// <summary>
        /// 判断null或DBNull或空字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsNullOrEmptyOrDBNull(object obj)
        {
            return ((obj is DBNull) || obj == null || string.IsNullOrEmpty(obj.ToString())) ? true : false;
        }

    }
}

   List<UnCompareDrug> t = CommonMap.MapToIEnumerable<UnCompareDrug>(dt).ToList();

 

datatable转换为list<model>

转载于:https://www.cnblogs.com/wlzhang/p/5809147.html

ExportTestCommand = new CommandBase(async l => { if (IQCListSelectItems == null || !IQCListSelectItems.Any()) { return; } try { List<string> iqcNoList = new List<string>{IQCListSelectItem.IqcNo }; var ret = await APIHelper.PostSendDtoAsync<List<IQCExportItemModel>>(ApiRoutes.IQCNoetailExportList, iqcNoList); if (ret == null || !ret.Any()) { return; } // 构建三级结构(使用 AutoMap 映射) List<IQCExportItemModel> threeLevelStructureList = new(); ret.ForEach(fe => { // 映射主单据 var currentfe = MapperHelper.AutoMap<IQCExportItemModel, IQCExportItemModel>(fe); currentfe.IQCExportDetailDtos = new List<IQCExportDetailModel>(); if (fe.IQCExportDetailDtos != null && fe.IQCExportDetailDtos.Any()) { fe.IQCExportDetailDtos.ForEach(detail => { // 映射明细 var currentDetail = MapperHelper.AutoMap<IQCExportDetailModel, IQCExportDetailModel>(detail); currentDetail.IQCExportDetailResultDtoList = new List<IQCExportDetailResultModel>(); if (detail.IQCExportDetailResultDtoList != null && detail.IQCExportDetailResultDtoList.Any()) { // 映射检测细项并转换为导出模型 detail.IQCExportDetailResultDtoList.ForEach(testItem => { // 从检测细项模型映射到导出模型 var exportTestItem = MapperHelper.AutoMap<IQCExportDetailResultModel, IQCExportModel>(testItem); // 补充主单据属性 exportTestItem.IqcNo = fe.IqcNo; exportTestItem.VendorCode = fe.VendorCode; exportTestItem.VendorName = fe.VendorName; exportTestItem.RtNo = fe.RtNo; // 补充明细属性 exportTestItem.ItemId = detail.ItemId; exportTestItem.IqcSolutionName = detail.IqcSolutionName; exportTestItem.LotQty = detail.LotQty; exportTestItem.SamplingQty = detail.SamplingQty; exportTestItem.TestQty = detail.TestQty; exportTestItem.DefectRate = detail.DefectRate; exportTestItem.Remark = detail.Remark; exportTestItem.DefectReason = detail.DefectReason; exportTestItem.HandlingMethod = detail.HandlingMethod; currentDetail.IQCExportDetailResultDtoList.Add(testItem); }); } else { // 无检测细项时添加空项 var emptyTestItem = new IQCExportDetailResultModel { IqcNo = fe.IqcNo, ItemId = detail.ItemId, PartNo = detail.PartNo, TestItemName = Langs.LangGetValue("NoTestItems") }; currentDetail.IQCExportDetailResultDtoList.Add(emptyTestItem); } currentfe.IQCExportDetailDtos.Add(currentDetail); }); } else { // 无明细时添加空明细 var emptyDetail = new IQCExportDetailModel { IqcNo = fe.IqcNo, PartNo = Langs.LangGetValue("NoDetails"), IQCExportDetailResultDtoList = new List<IQCExportDetailResultModel>() }; currentfe.IQCExportDetailDtos.Add(emptyDetail); } threeLevelStructureList.Add(currentfe); }); List<IQCExportModel> exportFlatList = new(); threeLevelStructureList.ForEach(main => { main.IQCExportDetailDtos.ForEach(detail => { if (detail.IQCExportDetailResultDtoList.Any()) { // 从检测细项映射到导出模型并补充属性 var items = MapperHelper.AutoMap<IQCExportDetailResultModel, IQCExportModel>(detail.IQCExportDetailResultDtoList); items.ForEach(item => { // 补充主单据和明细中未被自动映射的属性 item.RtNo = main.RtNo; item.IqcSolutionName = detail.IqcSolutionName; item.LotQty = detail.LotQty; item.SamplingQty = detail.SamplingQty; }); exportFlatList.AddRange(items); } else { // 无检测细项时用明细属性构建导出项 var emptyExportItem = MapperHelper.AutoMap<IQCExportDetailModel, IQCExportModel>(detail); MapperHelper.AutoMap(main, emptyExportItem); // 补充主单据属性 exportFlatList.Add(emptyExportItem); } }); }); // 执行导出 if (exportFlatList.Any()) { DataTable dtData = ImportHelper.ObjectToTable(exportFlatList, Langs); long timestamp = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).Ticks / 10000; string fileName = $"IQCExport_{timestamp}.xlsx"; SaveFileDialog saveFileDialog = new() { Filter = "Excel Files|*.xlsx", Title = Langs.LangGetValue("SelectExportPath"), FileName = fileName, DefaultExt = "xlsx", OverwritePrompt = true, RestoreDirectory = true, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { ImportHelper.ExportDataTable(dtData, saveFileDialog.FileName); new Process { StartInfo = new ProcessStartInfo(saveFileDialog.FileName) { UseShellExecute = true } }.Start(); MESGrowl.MESSuccess(Langs.LangGetValue("ExportSuccess")); } } else { MESGrowl.MESInfo(Langs.LangGetValue("NoValidDataToExport")); } } catch (Exception ex) { return; } });这个代码是什么意思,结构是什么
最新发布
08-08
点击查询没数据, public List<DeptmentQuery> search() { departments = new ArrayList<>(); /* List<DeptmentDm> deptmentDms = deptmentSerivce.getDeptmentInfoList(0, 10, getQueryMap(), new HashMap<>()); for (DeptmentDm deptmentDm : deptmentDms) { DeptmentQuery deptmentQuery = new DeptmentQuery(); deptmentQuery.setAddr(deptmentDm.getAddr()); deptmentQuery.setName(deptmentDm.getName()); deptmentQuery.setId(deptmentDm.getId()); deptmentQuery.setUpdateTime(deptmentDm.getUpdateTime()); deptmentQuery.setCreateTime(deptmentDm.getCreateTime()); if (departments == null) { departments = new ArrayList<DeptmentQuery>(); } departments.add(deptmentQuery); }*/ lazyDepartments = new LazyDataModel() { @Override public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) { Map<String, String> queryMap = getQueryMap(); // 调用服务层获取分页数据 List<DeptmentDm> deptmentDms = deptmentSerivce.getDeptmentInfoList( first, pageSize, queryMap, new HashMap<>() ); // 转换数据模型 List<DeptmentQuery> result = new ArrayList<>(); for (DeptmentDm dm : deptmentDms) { DeptmentQuery query = new DeptmentQuery(); query.setAddr(dm.getAddr()); query.setName(dm.getName()); query.setId(dm.getId()); query.setUpdateTime(dm.getUpdateTime()); query.setCreateTime(dm.getCreateTime()); departments.add(query); result.add(query); } // List<DeptmentDm> getList = deptmentSerivce.getDeptmentInfoList(first, pageSize, queryMap, new HashMap<>()); this.setRowCount(deptmentDms.size()); return result; } @Override public String getRowKey(Object rowdata) { if (rowdata instanceof Map) { DeptmentQuery row = (DeptmentQuery) rowdata; return row.getId().toString(); } return ""; } }; return departments; }, <div class="ui-inputgroup" style="display:inline-block;"> <p:commandButton icon="fa fa-search" value="查询" action="#{departmentBean.search}" update="dataTableId" style="width:95px;"/> </div>, <p:dataTable id="dataTableId" widgetVar="dataTableId" value="#{departmentBean.departments}" var="dept" styleClass="data-table centered-table" paginator="true" rows="6" paginatorPosition="bottom" rowsPerPageTemplate="5,10,20" lazy="true" paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"> <!-- 操作列 --> <p:column headerText="操作" style="width: 10%; text-align: center;"> <div style="display: flex; justify-content: center; gap: 8px;"> <p:commandLink update="@form:createDept" value="修改" action="#{departmentBean.openUpdateDeptDialog(dept)}" styleClass="centered-link" /> <p:commandLink update="@form:createDept" value="删除" action="#{departmentBean.deleteDept(dept)}" styleClass="centered-link" /> </div> </p:column> <!-- ID列 --> <p:column headerText="ID" style="width: 10%; text-align: center;"> <h:outputText value="#{dept.id}" style="display: block; text-align: center;" /> </p:column> <!-- 名称列 --> <p:column headerText="部门名称" style="width: 20%; text-align: center;"> <h:outputText value="#{dept.name}" style="display: block; text-align: center;" /> </p:column> <!-- 地址列 --> <p:column headerText="部门地址" style="width: 30%; text-align: center;"> <h:outputText value="#{dept.addr}" style="display: block; text-align: center;" /> </p:column> <!-- 创建时间列 --> <p:column headerText="创建时间" style="width: 20%; text-align: center;"> <h:outputText value="#{dept.createTime}" style="display: block; text-align: center;"> <f:convertDateTime pattern="yyyy-MM-dd HH:mm" /> </h:outputText> </p:column> <!-- 更新时间列 --> <p:column headerText="更新时间" style="width: 20%; text-align: center;"> <h:outputText value="#{dept.updateTime}" style="display: block; text-align: center;"> <f:convertDateTime pattern="yyyy-MM-dd HH:mm" /> </h:outputText> </p:column> </p:dataTable>
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值