C# DataTable通过反射转实体类

2021-06-08 11:03

阅读:297

标签:system   Fix   str   efi   exce   null   new t   tab   ==   

using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace MySqlHelper { public static class DataTableToModel { /// /// DataTable通过反射获取单个像 /// public static T ToSingleModel(this DataTable data) where T : new() { try { T t = data.GetList(null, true).Single(); return t; } catch (Exception e) { return new T(); } } /// /// DataTable通过反射获取单个像 /// 前缀 /// 是否忽略大小写,默认不区分 /// public static T ToSingleModel(this DataTable data, string prefix, bool ignoreCase = true) where T : new() { T t = data.GetList(prefix, ignoreCase).Single(); return t; } /// /// DataTable通过反射获取多个对像 /// /// /// /// public static List ToListModel(this DataTable data) where T : new() { List t = data.GetList(null, true); return t; } /// /// DataTable通过反射获取多个对像 /// /// 前缀 /// 是否忽略大小写,默认不区分 /// private static List ToListModel(this DataTable data, string prefix, bool ignoreCase = true) where T : new() { List t = data.GetList(prefix, ignoreCase); return t; } private static List GetList(this DataTable data, string prefix, bool ignoreCase = true) where T : new() { List t = new List(); int columnscount = data.Columns.Count; if (ignoreCase) { for (int i = 0; i )) { p.SetValue(model, Convert.ChangeType(data.Rows[i][j], p.PropertyType.GetGenericArguments()[0]), null); } else { p.SetValue(model, Convert.ChangeType(data.Rows[i][j], p.PropertyType), null); } } catch (Exception x) { throw x; } } break; } } } t.Add(model); } } catch (Exception ex) { throw ex; } return t; } } }

C# DataTable通过反射转实体类

标签:system   Fix   str   efi   exce   null   new t   tab   ==   

原文地址:https://blog.51cto.com/12268222/2377994


评论


亲,登录后才可以留言!