1. 程式人生 > >反射使用 非空表向空表賦值

反射使用 非空表向空表賦值

應用場景

  現有兩張表,表A,表B(歷史表) ,需將表A中與表B中相同欄位的資料進行賦值到表B中

分為兩種實現情況

一、表B中沒有任何資料

二、表B中有資料非空

 /// <summary>
    /// 實體轉換類
    /// </summary>
    public class EntityCoverter
    {
        /// <summary>
        /// 將源實體轉換到空的實體類中
        /// </summary>
        /// <typeparam name="T1"></typeparam>
/// <typeparam name="T2"></typeparam> /// <param name="source"></param> /// <returns></returns> public static T2 Covert<T1, T2>(T1 source) { T2 result = default(T2); PropertyInfo[] pi = typeof(T2).GetProperties(); PropertyInfo[] pi1
= typeof(T1).GetProperties(); result = Activator.CreateInstance<T2>(); for (int i = 0; i < pi.Length; i++) { PropertyInfo temp = pi1.Where(t => t.Name == pi[i].Name).FirstOrDefault(); if (temp != null) {
try { pi[i].SetValue(result, temp.GetValue(source, null), null); } catch(Exception ex) { } } } return result; } /// <summary> /// 將源實體轉換到非空的實體中 /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> /// <param name="source"></param> /// <param name="destination"></param> /// <returns></returns> public static T2 Covert<T1, T2>(T1 source,T2 destination) { PropertyInfo[] pi = typeof(T2).GetProperties(); PropertyInfo[] pi1 = typeof(T1).GetProperties(); for (int i = 0; i < pi.Length; i++) { PropertyInfo temp = pi1.Where(t => t.Name == pi[i].Name).FirstOrDefault(); if (temp != null) { try { pi[i].SetValue(destination, temp.GetValue(source, null), null); } catch { } } } return destination; } }

呼叫方法

           
            var list =  獲取表A值,將表A的值處理成一個list集合ToList();
            List<B> result = new List<B>();
            foreach (var item in list)
            {
                var simple = EntityCoverter.Covert<A, B>(item);
                result.Add(simple);
            }
          return  result;