AutoMapper的使用在NET core中的使用记录
关于AutoMapper的用处以及主要便利指出请参考官方文档,本文章仅记录自己使用的过程及代码;
安装
在项目中涉及到的类包括:Account,AccountCondition,AutoMapperConfig
代码如下:
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方法中 中添加如下代码:
' services.AddAutoMapper(cfg=>cfg.AddProfile<AutoMapperConfig>());
无需做其他配置;
在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);
测试结果:如下
{ "email": "ken", "pageSize": 5, "pageNum": 1, "offset": 0, "needPager": false }