Automatically map entities and models using AutoMapper
AutoMapper is an object mapping tool that can automatically map entity objects and model objects, reducing the workload of manual mapping and improving development efficiency. In addition, Mapster is also a high-performance object mapping tool that supports source generation code and has better performance. AutoMapper is more popular, more mature, more stable, easier to use, more flexible, more powerful, more comprehensive, and more popular than Mapster. AutoMapper is part of the .NET Foundation, an open source project, and a very excellent object mapping tool.
Install the NuGet package
dotnet add package AutoMapper
Register AutoMapper in dependency injection
builder.Services.AddAutoMapper(Assembly.GetExecutingAssembly());
Create mapping configuration file
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<User, UserDto>();
CreateMap<UserDto, User>();
}
}
Mapping entities and models using AutoMapper
public class UserService
{
private readonly IMapper _mapper;
public UserService(IMapper mapper)
{
_mapper = mapper;
}
public UserDto GetUser(int id)
{
var user = _dbContext.Users.Find(id);
return _mapper.Map<UserDto>(user);
}
public void UpdateUser(UserDto userDto)
{
var user = _mapper.Map<User>(userDto);
_dbContext.Users.Update(user);
_dbContext.SaveChanges();
}
}
Paging mode
There are two common paging modes, one is based on page number and page size, and the other is based on cursor and page size.