關於AutoMapper的用處以及主要便利指出請參考官方文檔,本文章僅記錄本身使用的過程及代碼;api
安裝app
在項目中涉及到的類包括:Account,AccountCondition,AutoMapperConfigide
代碼以下:測試
public class Account { [Column(Name = "id", IsKey = true)] public int Id { get; set; } [Column(Name = "user_name")] public string Name { get; set; } [Column(Name = "user_email")] public string Email { get; set; } [Column(Name = "pass_word")] public string PassWord { get; set; } [Column(Name = "address")] public string Address { get; set; } [Column(Name = "phone_no")] public string Phone { get; set; } [Column(Name="Imageurl")] public string ImagerUrl { get; set; } [Column(Name = "wechat_id")] public string WechatId{get;set;} }
1 public class AccountCondition 2 { 3 public string Email { get; set; } 4 public string Name { get; set; } 5 public int PageSize { get; set; } = 5; 6 public int PageNum { get; set; } = 1; 7 public int Offset { get; set; } 8 public bool NeedPager { get; set; } 9 }
1 public class AutoMapperConfig:Profile 2 { 3 public AutoMapperConfig() 4 { 5 CreateMap<Account, AccountCondition>() 6 .ForMember(d => d.Email, option => option.MapFrom(s => s.Name)) 7 .ForMember(d => d.Name, option => option.MapFrom(s => s.Email)); 8 } 9 }
在startup中的 ConfigureServices方法中 中添加以下代碼:url
' services.AddAutoMapper(cfg=>cfg.AddProfile<AutoMapperConfig>());spa
無需作其餘配置;code
在controller 中配置以下:對象
[Route("api/[controller]")] public class AccountController : BaseController { IAccountService _accountService; IMapper _mapper; //private IHostingEnvironment _hostingEnvironment; //private readonly IConfiguration _config; public AccountController(IAccountService accountService, IMapper mapper, IHostingEnvironment hostingEnvironment, IConfiguration config) : base(hostingEnvironment, config) { _accountService =accountService; _mapper = mapper; } [Route("test")] [HttpGet] public IActionResult Test() { var account = new Account() { Active = "Y", Name = "ken", Email = "1234@123.com", }; var result = _mapper.Map<AccountCondition>(account); return Ok(result); } }
其中使用的對象映射如: var result = _mapper.Map<AccountCondition>(account);blog
測試結果:以下文檔
{ "email": "ken", "pageSize": 5, "pageNum": 1, "offset": 0, "needPager": false }