reflection 跟 autoMap

  • 258
  • 0
  • 2017-01-20

reflection 跟 autoMap 的演變

降低DAO 裡面 將DS 塞入 object作法

1. 

public static List<T> ConvertData<T>(SqlDataReader sdr)
     {
         List<T> list = new List<T>();
         Type type = typeof(T);
         PropertyInfo[] properties = type.GetProperties();
         while (sdr.Read())
         {
             T model = Activator.CreateInstance<T>();
             for (int i = 0; i < properties.Length; i++)
             {
                 for (int j = 0; j < sdr.FieldCount; j++)
                 {
                     if (properties[i].Name == sdr.GetName(j))
                     {
                         Object value =sdr[j];
                         properties[i].SetValue(model, value, null);
                     }
                 }
             }
             list.Add(model);
         }
         return list;
     }

Source: http://www.cnblogs.com/xiaofeixiang/p/4018066.html

- 其實reflection 還有好多建置instance的功用。但不是這篇主題。

2. 使用AutoMapper

只要有對應好的object 即可自動map

source: http://kevintsengtw.blogspot.tw/2013/04/automapper.html

-------updated: 2016-07-23---------

上敘介紹為舊版,  新版5.0 已經不能使用 Mapper.CreateMap<object, object>(); 可這樣用:

(使用Profile方式這裡先不介紹)

var config2 = new MapperConfiguration(c =>
{
    c.CreateMap<dgvOrderDetailViewModel, Product>();                   
});
IMapper mapper = config2.CreateMapper();

_ProductList = mapper.Map<List<dgvOrderDetailViewModel>, List<Product>>(_dgvOrderDetailVMList);

上面是要做list 物件轉換, 如果要做到子物件也轉換的話, 要在create configuration時建立, 以下:

var config = new MapperConfiguration(c =>
        {
            c.CreateMap<CustomObjectSource, CustomObjectDest>();
            c.CreateMap<Source, Destination>()
              .AfterMap((Src, Dest) => Dest.NestedProp = new CustomObjectDest
              {
                  Key = Src.NestedProp.Key,
                  Value = Src.NestedProp.Value
              });
        });

Source: http://stackoverflow.com/a/35404845

還可以使用ForMember 做欄位的對應, 跟 ignore 不想要對應到的欄位

//對應的
.ForMember(des => des.productId, opts => opts.MapFrom(src => src.productId));

//不想要對應的
.ForMember(des => des.productId, opts => opts.Ignore());