这是数据库开发中经常遇到的问题,当然,这可以用现成的ORM框架来解决,但有些时候,如果DataSet/DataTable是第三方接口返回的,ORM就不方便了,还得自己处理。
反射自然必不可少的,另外考虑到DataTable中的ColumnName通常与Model的PropertyName并不严格对应,可以用Attribute来记录这种映射关系。
步骤1:先创建一个DataFieldAttribute类
using System; 2 3 namespace Jimmy.ORM 4 { 5 [AttributeUsage(AttributeTargets.Property)] 6 public sealed class DataFieldAttribute:Attribute 7 { 8 /// <summary> 9 /// 表对应的字段名 10 /// </summary> 11 public string ColumnName { set; get; } 12 13 public DataFieldAttribute(string columnName) 14 { 15 ColumnName = columnName; 16 } 17 } 18 }
步骤2:在Model/Entity的Class成员上,应用DataField特性,参见下面的代码:
using System; namespace Jimmy.ORM.Entity { [Serializable] public class ProductEntity : DataEntityBase { [DataField("PRODUCT_NO")] public string ProductNo { set; get; } [DataField("PRODUCT_ID")] public int ProductId { set; get; } [DataField("PRODUCT_NAME")] public string ProductName { set; get; } public override string ToString() { return string.Format("ProductNo:{1}{0}ProductId:{2}{0}ProductName:{3}", Environment.NewLine, ProductNo, ProductId, ProductName); } } }
步骤3:该反射出场了,为了方便起见,封装了一个DataConvert类
using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace Jimmy.ORM { /// <summary> /// 将DataRow/DataTable转换成Entity/Entity列表 /// </summary> public static class DataConvert<T> where T : DataEntityBase, new() { /// <summary> /// 将DataRow行转换成Entity /// </summary> /// <param name="dr"></param> /// <returns></returns> public static T ToEntity(DataRow dr) { T entity = new T(); Type info = typeof(T); var members = info.GetMembers(); foreach (var mi in members) { if (mi.MemberType == MemberTypes.Property) { //读取属性上的DataField特性 object[] attributes = mi.GetCustomAttributes(typeof(DataFieldAttribute), true); foreach (var attr in attributes) { var dataFieldAttr = attr as DataFieldAttribute; if (dataFieldAttr != null) { var propInfo = info.GetProperty(mi.Name); if (dr.Table.Columns.Contains(dataFieldAttr.ColumnName)) { //根据ColumnName,将dr中的相对字段赋值给Entity属性 propInfo.SetValue(entity, Convert.ChangeType(dr[dataFieldAttr.ColumnName], propInfo.PropertyType), null); } } } } } return entity; } /// <summary> /// 将DataTable转换成Entity列表 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<T> ToList(DataTable dt) { List<T> list = new List<T>(dt.Rows.Count); foreach (DataRow dr in dt.Rows) { list.Add(ToEntity(dr)); } return list; } } }
步骤4:测试
using System; using System.Data; using Jimmy.ORM.Entity; namespace Jimmy.ORM.Test { class Program { static void Main() { DataTable dt = new DataTable(); dt.Columns.Add("PRODUCT_NO"); dt.Columns.Add("PRODUCT_ID"); dt.Columns.Add("PRODUCT_NAME"); dt.Rows.Add("00001", 1, "手机"); dt.Rows.Add("00002", 2, "服装"); var products = DataConvert<ProductEntity>.ToList(dt); foreach (var entity in products) { Console.WriteLine(entity); } Console.Read(); } } }
时间: 2024-11-09 13:51:17