c#mapper implements two different tables to add data to the same table
Mapper implements two different tables to add data to the same table
mapper, role of reflection, AutoMapper
What I understand:
1. The essence is that different objects are mapped so that the target object gets the value of the original object;
The difference between reflection and Mapper, how to implement it
1. Values are all assigned through mapping, so can it be implemented through reflection?
Yes, they are essentially the same.
Code display
1、通过mapper去给对象赋值
Mapper.CreateMap<H21ShipmentDataModel, ED_JMWmsOcvDataProduct>().ForMember(ed => ed.LineNo, op => op.MapFrom(h => "H21")).ForMember(ed=> ed.transSuccessFlag, op => op.MapFrom(h21 => h21.transSuccessFlag) .ForMember(ed => ed.EventDate, opt => opt.MapFrom(h21 => h21.Date)).ForMember(ed => ed.LineNo, op => op.ignore(h21=>h21.LineNo)));
2、`通过反射给对象赋值
//解决问题,两个类字段相同,但是类名不一样,如何进行赋值,通过反射进行逐一字段读取然后赋值
var DuanXinType = new DuanXin();
DuanXinType.RECEIVE_LOGIN_NAME = "cwh";
DuanXinType.RECEIVE_Number = "13800138000";
//获取对象类型
var typeduanxin = typeof(DuanXin);
//获取对象属性
var PropertyInfoDuanxin = typeduanxin.GetProperties();
WeChat pWeChat = new WeChat();
var typeWeChat = typeof(WeChat);
var PropertyInfosWeChat = typeWeChat.GetProperties();
//给新对象赋值
foreach (var itemduanxin in PropertyInfoDuanxin)
{
var objDuanXinType = itemduanxin.GetValue(DuanXinType);
foreach (var itemWeChat in PropertyInfosWeChat)
{
if (itemduanxin.Name == itemWeChat.Name)
{
itemWeChat.SetValue(pWeChat, objDuanXinType, null);
}
}
}
> 解析:
> 1、ForMember(ed => ed.LineNo, op => op.MapFrom(h => "H21")):意思是将 给目标表字段赋值,因为原表中没有该字段,是目标表新加的字段。
> 2、ForMember(ed=> ed.transSuccessFlag, op => op.MapFrom(h21 => h21.transSuccessFlag) 将原表的字段给目标表字段,这种相同字段名之间的映射其实可以省略。
> 3、ForMember(ed => ed.EventDate, opt => opt.MapFrom(h21 => h21.Date))这个就是不同的字段值映射,需要手动去关联这两个字段
> 4、ForMember(ed => ed.LineNo, op => op.ignore(h21=>h21.LineNo)) :意思是忽略原表中的字段不映射过来