现在有2个实体(A、B),2个实体中的部分字段是相同的,现在把A实体获取的值赋值给B实体,利用AutoMapper实体映射可以轻松解决
实体中不同名称之间的映射可以这样写
Mapper.Initialize(x =>
x.CreateMap<WorldA, WorldB>()
.ForMember(d => d.AGE, opt => {
opt.MapFrom(s => s.name);
})
);
注意:字段名称相同的类型一定也要相同不然会报错的
//第一步初始化
Mapper.Initialize(cfg =>
{
cfg.CreateMap<WorldA, WorldB>();
});
List<WorldA> worldAs = new List<WorldA>()
{
new WorldA() { id = , wewe = "测试1",name="98k" },
new WorldA() { id = , wewe = "测试2",name="98k" },
new WorldA() { id = , wewe = "测试3",name="98k" },
};
//A实体值赋给B实体
List<WorldB> b = Mapper.Map<List<WorldA>, List<WorldB>>(worldAs).ToList();
public class WorldA
{
public int id { get; set; }
public string wewe { get; set; } public string name { get; set; }
}
public class WorldB
{
public int id { get; set; }
public string wewe { get; set; } public string AGE { get; set; } public string money { get; set; }
}
值为null的处理
Mapper.Initialize(x => x.AddProfile<UserProfile>());
List<WorldA> worldAs = new List<WorldA>()
{
new WorldA() { id = , wewe = "测试1",name=null },
new WorldA() { id = , wewe = "测试2",name="98k" },
new WorldA() { id = , wewe = "测试3",name="98k" },
}; //A实体值赋给B实体
List<WorldB> b = Mapper.Map<List<WorldA>, List<WorldB>>(worldAs).ToList();
public class UserProfile : Profile
{
protected override void Configure()
{
CreateMap<WorldA, WorldB>()
.ForMember(d => d.AGE, opt => opt.MapFrom(s => s.name))
.ForMember(d => d.AGE, opt => opt.NullSubstitute("值为空")
);
CreateMap<WorldA, WorldB>()
.ForMember(d => d.money, opt => opt.MapFrom(s => s.name))
.ForMember(d => d.money, opt => opt.NullSubstitute("值为空")
);
}
}