table 转实体
public class Table2Entity<T> where T : class,new() { public static List<T> GetEntitys(DataTable dt) { Dictionary<string, string> columns = new Dictionary<string, string>(); foreach (DataColumn item in dt.Columns) { columns.Add(item.ColumnName.Trim().ToLower(), item.ColumnName); } List<T> result = new List<T>(); var proptetis = typeof(T).GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); foreach (DataRow dr in dt.Rows) { T obj = new T(); foreach (var item in proptetis) { var attributes = item.GetCustomAttributes(typeof(RenameAttribute), true); var columnName = (attributes != null && attributes.Length > 0) ? ((RenameAttribute)(attributes[0])).Name.Trim().ToLower() : item.Name.Trim().ToLower(); if (columns.Keys.Contains(columnName)) { var mt = item.GetSetMethod(true); var value = dr[columns[columnName]]; if (value == null || value == DBNull.Value || string.IsNullOrWhiteSpace(value.ToString())) continue; if (item.PropertyType == typeof(string)) mt.Invoke(obj, new object[] { value.ToString() }); else if (item.PropertyType == typeof(int) || item.PropertyType == typeof(int?)) mt.Invoke(obj, new object[] { Convert.ToInt32(value) }); else if (item.PropertyType == typeof(long) || item.PropertyType == typeof(long?)) mt.Invoke(obj, new object[] { Convert.ToInt64(value) }); else if (item.PropertyType == typeof(double) || item.PropertyType == typeof(double?)) mt.Invoke(obj, new object[] { Convert.ToDouble(value) }); else if (item.PropertyType == typeof(decimal) || item.PropertyType == typeof(decimal?)) mt.Invoke(obj, new object[] { Convert.ToDecimal(value) }); else if (item.PropertyType == typeof(DateTime) || item.PropertyType == typeof(DateTime?)) mt.Invoke(obj, new object[] { Convert.ToDateTime(value) }); else if (item.PropertyType == typeof(float) || item.PropertyType == typeof(float?)) mt.Invoke(obj, new object[] { float.Parse(value.ToString()) }); else if (item.PropertyType == typeof(bool)) mt.Invoke(obj, new object[] { bool.Parse(value.ToString()) }); else if (item.PropertyType.BaseType == typeof(System.Enum)) { mt.Invoke(obj, new object[] { Convert.ToInt32(value) }); } } } result.Add(obj); } return result; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库