Automapper使用

//简单用法
Mapper.Initialize(x => x.CreateMap<User, UserDto>());
var dto = Mapper.Map<UserDto>(user);


//属性名称不同
Mapper.Initialize(x => x.CreateMap<User, UserDto>()
         .ForMember(d =>d.Name2, opt => {opt.MapFrom(s => s.Name);}));
var dto = Mapper.Map<UserDto>(user);


//空值替换
Mapper.Initialize(x => x.CreateMap<User, UserDto>()
         .ForMember(d =>d.Name2, opt => {opt.MapFrom(s => s.Name);})
         .ForMember(d => d.Name2, opt => opt.NullSubstitute("值为空")));
var dto = Mapper.Map<UserDto>(user);


//忽略属性
Mapper.Initialize(x => x.CreateMap<User, UserDto>()
         .ForMember("Name", opt => opt.Ignore()));
var dto = Mapper.Map<UserDto>(user);


//使用profile配置
public class UserProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<User, UserDto>()
                .ForMember(d => d.Name2, opt =>
                {
                    opt.MapFrom(s => s.Name);
                });
        }
    }

Mapper.Initialize(x => x.AddProfile<UserProfile>());
var dto = Mapper.Map<UserDto>(user);


 

posted @ 2018-07-10 15:30  kerwin cui  阅读(194)  评论(0编辑  收藏  举报