AutoMapper模型映射
1:安装2个包
AutoMapper
和AutoMapper.Extensions.Microsoft.DependencyInjection
实体类:
[SugarTable("UserInfo")]
public class UserInfo
{
[SqlSugar.SugarColumn(IsPrimaryKey =true,IsIdentity =true)]
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
实体Dto
namespace Model.ViewModel
{
public class UserInfoDto
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
2:新建文件夹Automapper
using AutoMapper;
using AutoMapper.Configuration;
using Model.Model;
using Model.ViewModel;
namespace webapi_demo.Automapper
{
public class AutomapperConfig: Profile
{
public AutomapperConfig()
{
CreateMap<UserInfo, UserInfoDto>();
}
}
}
3:Program.cs注入
using Common;
using System.Reflection;
using webapi_demo.Automapper;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAutoMapper(typeof(AutomapperConfig));
4 :控制器引用
public UserInfoController(UserInfoService UserService, IMapper map)
{
_service = UserService;
_map = map;
}
[HttpGet]
public async Task<UserInfoDto> GetUser(int id)
{
var user = await _service.QueryByID(id);
UserInfoDto dto = new UserInfoDto();
_map.Map(user, dto);
return dto;
}
5:结果图
本文来自博客园,作者:.net&new,转载请注明原文链接:https://www.cnblogs.com/wugh8726254/p/16811163.html