参考
【C#】AutoMapper 使用手册 - 丹枫无迹 - 博客园 (cnblogs.com)
环境搭建
AutoMapper.Extensions.Microsoft.DependencyInjection
服务注册
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
创建实体类
转换前类
csharp
namespace AutoMapper_01.Entities
{
public class User
{
public int Id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public bool gender { get; set; }
public DateTime DateOfBirth { get; set; }
}
}
转换后类
csharp
namespace AutoMapper_01.Entities
{
public class UserDto
{
public int Id { get; set; }
public string name { set;get; }
public bool sex { get; set; }
public int Age { get; set; }
}
}
创建映射关系
typescript
using AutoMapper;
using AutoMapper_01.Entities;
namespace AutoMapper_01.profiles
{
public class UserProfile:Profile
{
public UserProfile()
{
CreateMap<User,UserDto>()
.ForMember(
dest=>dest.sex,
opt => opt.MapFrom(src=>src.gender)
)
.ForMember(
dest => dest.name,
opt => opt.MapFrom(src => $"{src.firstName} {src.lastName}")
)
.ForMember(
dest => dest.Age,
opt => opt.MapFrom(src => DateTime.Now.Year - src.DateOfBirth.Year)
);
}
}
}
测试
ini
using AutoMapper;
using AutoMapper_01.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace AutoMapper_01.Controllers
{
[ApiController]
[Route("[controller]")]
public class Demo : ControllerBase
{
private readonly IMapper _mapper;
public Demo(IMapper mapper)
{
_mapper = mapper;
}
[HttpGet(Name = "Test")]
public Object Get()
{
User user = new User{
Id = 1,
firstName = "f1",
lastName = "l1",
gender = true,
DateOfBirth = new DateTime(1970,10,6) ,
};
Console.WriteLine(user.Id);
var userDto = _mapper.Map<UserDto>(user);
User user2 = new User{
Id = 2,
firstName = "f2",
lastName = "l2",
gender = false,
DateOfBirth = new DateTime(2019, 1, 26),
};
List<User> users = new List<User>();
users.Add(user);
users.Add(user2);
var userDtos = _mapper.Map<List<UserDto>>(users);
return new {
userDto = userDto,
userDtos = userDtos
};
}
}
}