AutoMapper使用
AutoMapper初始化 在global.axax的Application_Start中使用AutoMapperConfiguration.Configure();
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BaseAsset.Api.Mappings { public class AutoMapperConfiguration { public static void Configure() { Mapper.Initialize(x => { //DomainToViewModelMappingProfile文件将被实例化并添加到配置中。 x.AddProfile<DomainToViewModelMappingProfile>(); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AutoMapper; using BaseAsset.Api.Models.Assets; using BaseAsset.Entities; using BaseAsset.Api.Models.Food; using BaseAsset.Api.Models.group; using BaseAsset.Entities.Dto; using BaseAsset.Api.Models.Enter; using BaseAsset.Api.Models.Home; using BaseAsset.Entities.CaseDto.Req; using BaseAsset.Entities.CaseEntities; using BaseAsset.Api.Models.service; using BaseAsset.Api.Models.Item; namespace BaseAsset.Api.Mappings { public class DomainToViewModelMappingProfile : Profile { public DomainToViewModelMappingProfile() { //来源,目标 CreateMap<en_enter_object, EnterObjectModel>(); CreateMap<en_enter_object, EnterObjectViewModel>().ForMember(d=>d.name,opt=> { opt.MapFrom(a => a.name + a.idcard);//重写映射规则 }); } } }
使用:
var enterObj = new EnterObjectViewModel();
enterObj = Mapper.Map<en_enter_object, EnterObjectViewModel>(obj);