這是資料庫開發中經常遇到的問題,當然,這可以用現成的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(); } } }