雲計算

.NET CORE 中用AutoMapper將實體轉Dto

在開發過程中,經常會碰到數據實體對象(Entity)和數據傳輸對象(Dto)的轉換,手寫代碼太煩太LOW,可以用 AutoMapper 按規則自動轉換。

1、安裝兩個依賴包,通過Nuget安裝

AutoMapper 
AutoMapper.Extensions.Microsoft.DependencyInjection //startup 中 services.AddAutoMapper(); 需要依賴此包。

2、在Startup中添加AutoMapper

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//添加對AutoMapper的支持,會查找所有程序集中繼承了 Profile 的類
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

}

3、創建AutoMapper映射規則,繼承 Profile

public class AutoMapperConfigs: Profile
{
    //添加你的實體映射關係.
    public AutoMapperConfigs()
    {
        //UserEntity轉UserDto.
        CreateMap<UserEntity, UserDto>()
            //映射發生之前
            .BeforeMap((source,dto) => {
                //可以較為精確的控制輸出數據格式
                dto.CreateTime = Convert.ToDateTime(source.CreateTime).ToString("yyyy-MM-dd");
            })
            //映射發生之後
            .AfterMap((source, dto) => {
                //code ...
            });

        //UserDto轉UserEntity.
        CreateMap<UserDto, UserEntity>();
    }

}

4、在Controller構造函數中注入IMapper,然後在方法中使用

public class UserController : Controller
{
 private readonly IMapper _mapper;
 public UserController(IMapper mapper)
 {
     _mapper = mapper;
 }

 [HttpGet]
 public JsonResult Get(int id=1)
 {
     //模擬數據
     var user = new UserEntity() { Id = id, UserName = "UserA" };
     //實體對象轉Dto對象
     var userDto = _mapper.Map<UserDto>(user);
     return new JsonResult(userDto);
 }

 [HttpGet]
 public JsonResult Get()
 {
     //模擬數據
     var users = new List<UserEntity>();
     for (int i=0;i<5;i++)
     {
         users.Add( new UserEntity() { Id = i, UserName = $"User{i}" });
     }
     
     //實體對象集合轉Dto對象集合
     var userDtos = _mapper.Map<List<UserDto>>(usesr);
     return new JsonResult(userDtos);
 }
 

}

雲服務器ECS地址:阿里雲·雲小站

Leave a Reply

Your email address will not be published. Required fields are marked *