1. 程式人生 > >.Net Core 中使用AutoMapper進行對象映射

.Net Core 中使用AutoMapper進行對象映射

ber figure str before git star config pan mpat

  官網:http://automapper.org/

  文檔:https://automapper.readthedocs.io/en/latest/index.html

  GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst

⒈安裝相關依賴

  AutoMapper

  AutoMapper.Extensions.Microsoft.DependencyInjection

⒉在Startup中添加AutoMapper

 1         public void ConfigureServices(IServiceCollection services)
2 { 3 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 4 5 //添加對AutoMapper的支持 6 services.AddAutoMapper(cfg => 7 { 8 cfg.AddProfile<AutoMapperConfig>(); 9 }, AppDomain.CurrentDomain.GetAssemblies());
10 }

⒊使用配置文件創建AutoMapper映射規則

 1 using AutoMapper;
 2 using AutoMapperTest.Entities;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Text;
 6 
 7 namespace AutoMapperTest.AutoMapper
 8 {
 9     public class AutoMapperConfig:Profile
10     {
11         public
AutoMapperConfig() 12 { 13 CreateMap<UsersInputDto, Users>().ForMember(d => d.username, u => u.MapFrom(s => s.uname)) //屬性名稱映射 14 .ForMember(d => d.password, u => u.MapFrom(s => s.pwd)) //屬性名稱映射 15 .ForMember(d => d.age, u => u.Condition(s => s.age >= 0 && s.age <= 120)) //對一些屬性做映射判斷 16 .BeforeMap((dto, ent) => ent.fullname = dto.firstname + "_" + dto.lastname) //對一些屬性做映射前處理 17 ; 18 } 19 } 20 }

⒋在代碼中使用AutoMapper

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using AutoMapper;
 6 using AutoMapperTest.Entities;
 7 using Microsoft.AspNetCore.Mvc;
 8 
 9 namespace AutoMapperCore.Controllers
10 {
11     public class UsersController : Controller
12     {
13         private readonly IMapper _mapper;
14         public UsersController(IMapper mapper)
15         {
16             this._mapper = mapper;
17         }
18         public IActionResult Index()
19         {
20             UsersInputDto input = new UsersInputDto()
21             {
22                 id = 1, firstname = "fan", lastname = "qi", uname = "fanqisoft", pwd = "admin", enabled = 1
23             };
24             
25             Users users = _mapper.Map<Users>(input);
26             return View();
27         }
28     }
29 }

.Net Core 中使用AutoMapper進行對象映射