自动实体转化
View Model/BU Entity/DB Entity 在这写了一个自动Transform的类。很给力。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace NESO.PreOrderService.ServiceImpl { public class AutoTransformersHandler { public static void Transform<T, F>(List<T> target, List<F> source) where F : new() { for (int i = 0; i < target.Count; i++) { F f = new F(); Transform<T, F>(target[i], f); source.Add(f); } } public static void Transform<T, F>(T target, F source) { PropertyInfo[] fromFields = null; PropertyInfo[] toFields = null; fromFields = typeof(T).GetProperties(); toFields = typeof(F).GetProperties(); SetProperties(fromFields, toFields, target, source); } public static void SetProperties(PropertyInfo[] fromFields, PropertyInfo[] toFields, object fromRecord, object toRecord) { PropertyInfo fromField = null; PropertyInfo toField = null; if (fromFields == null) { return; } if (toFields == null) { return; } for (int f = 0; f < fromFields.Length; f++) { fromField = (PropertyInfo)fromFields[f]; for (int t = 0; t < toFields.Length; t++) { toField = (PropertyInfo)toFields[t]; if (fromField.Name != toField.Name) { continue; } toField.SetValue(toRecord, fromField.GetValue(fromRecord, null), null); break; } } } } }