AutoMapper 基本使用

AutoMapper 基本使用1 Initialize Mapper 初始化 Mapper Initialize x gt x CreateMap Destination Source Mapper Initialize cfg gt cfg CreateMap Aliens Person Mapper Initialize cfg Aliens Person Destination Source

1、Initialize:Mapper 初始化

Mapper.Initialize(x => x.CreateMap<Destination, Source>() ); Mapper.Initialize(cfg => { cfg.CreateMap<Aliens, Person>(); }); Mapper.Initialize(cfg => { cfg.CreateMap<Foo, FooDto>(); cfg.CreateMap<Bar, BarDto>(); });

2、映射前、映射后 操作

Mapper.Initialize(x => x.CreateMap<Destination, Source>() .BeforeMap((src, dest) => src.InfoUrl = "https://" + src.InfoUrl) .AfterMap((src, dest) => src.name = "真棒" + src.name)); cfg.CreateMap<ClassBannerDo, ClassBannerDto>() .BeforeMap((source, dto) => { if (!string.IsNullOrEmpty(source.ImgUrl)) source.ImgUrl = StringPlus.GetWebConfigKey("ImageDomain") + source.ImgUrl; if (!string.IsNullOrEmpty(source.Thumbnail)) source.Thumbnail = StringPlus.GetWebConfigKey("ImageDomain") + source.Thumbnail; }); cfg.CreateMap<StudentInoutDo, StudentInoutDto>() // f.字符串 f => 枚举描述 .ForMember(f => f.InOutDisplay, f => f.MapFrom(m => m.Inout == 1 ? EnumInout.In.GetEnumDescription() : EnumInout.Out.GetEnumDescription())); // f.枚举 f => 枚举 .ForMember(f => f.InOutEnum, f => f.MapFrom(m => m.Inout == 1 ? EnumInout.In : EnumInout.Out)) // 实体对象序列化 json 字符串 .ForMember(f => f.School, f => f.MapFrom(m => JsonConvert.SerializeObject(m.School))) .ReverseMap() // 数据库中为 json 字符串,反序列化 实体对象 .ForMember(f => f.School, f => f.MapFrom(m => JsonConvert.DeserializeObject<SchoolDo>(m.School))); public enum EnumInout { Normal = 0, [Description("进校")] In = 1, [Description("出校")] Out = 2 }

3、条件映射

Mapper.Initialize(x => x.CreateMap<Destination, Source>() .ForMember(dest => dest.InfoUrl, opt => opt.Condition(dest => dest.InfoUrl == "www.cnblogs.com/zaranet1")) .ForMember(...(.ForMember(...))));

4、多类映射

public static void Configure() { Mapper.Initialize(cfg => { cfg.AddProfile<DestinationSourceProfile>(); cfg.AddProfile(new StudentSourceProfile()); }); } 

5、CreateMap【配置 AutoMapper】 与 Mapper.Map【执行映射,执行 mapping】

Mapper.CreateMap<Order, OrderDto>(); OrderDto dto = Mapper.Map<Order, OrderDto>(order); var fooDto = Mapper.Map<FooDto>(foo); var barDto = Mapper.Map<BarDto>(bar);

6、忽略字段,隐藏字段

Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());

==============.NET Core AutoMapper==============

1、Nuget安装

AutoMapper        AutoMapper.Extensions.Microsoft.DependencyInjection  //需要依赖注入AutoMapper,需要下载该包。

2、在Startup中添加AutoMapper

public void ConfigureServices(IServiceCollection services) {     services.AddMvc();     //添加对AutoMapper的支持     services.AddAutoMapper(typeof(WebMapperInit)); }

3、创建AutoMapper映射配置文件

using AutoMapper; using Hospital.Entity; using Hospital.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hospital.WebAPI { public class WebMapperInit : Profile { public WebMapperInit() { CreateMap<base_patient, PatientRequest>() .ForMember(d => d.Id, option => option.MapFrom(s => s.id)) .ForMember(d => d.UserId, option => option.MapFrom(s => s.user_id)) .ForMember(d => d.HospitalId, option => option.MapFrom(s => s.hospital_id)) .ForMember(d => d.CreatedTime, option => option.MapFrom(s => s.created_time)) .ForMember(d => d.ModifyTime, option => option.MapFrom(s => s.modify_time)) .ForMember(d => d.Status, option => option.MapFrom(s => s.status)) .ReverseMap(); } } }

4、Controller

using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Hospital.Entity; using Hospital.Models; using Hospital.Repository; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Hospital.WebAPI.Controllers { [Route("")] [ApiController] public class PatientController : ControllerBase { private readonly IPatientRepository _patientRepo; private readonly IMapper _mapper; public PatientController(IMapper mapper, IPatientRepository patientRepo) { _patientRepo = patientRepo; _mapper = mapper; } [HttpPost] public CreatePatientResponse C([FromBody]PatientRequest request) { request.HospitalId = Guid.NewGuid(); _patientRepo.AddWithGuid(_mapper.Map<base_patient>(request)); return new CreatePatientResponse(); } } }

5、静态文件

-- var config = new MapperConfiguration(cfg => cfg.CreateMap<E, T>()); var mapper = config.CreateMapper(); mapper.Map<T> -- public UserRepository(AssetDbContext context) : base(context) { var config = new MapperConfiguration(cfg => cfg.CreateMap<UserDto, UserDo>()); var mapper = config.CreateMapper(); }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/230206.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号