使用AutoMapper
1、在控制台中
namespace StudyAutoMapper { public class Foo { public int ID { get; set; } public string Name { get; set; } } public class FooDto { public int ID { get; set; } public string Name { get; set; } } public class AutoMapperProfile : Profile { public AutoMapperProfile() //配置AutoMapper { CreateMap<Foo, FooDto>(); } } internal class Program { static void Main(string[] args) { var config = new MapperConfiguration(cfg => { cfg.AddProfile<AutoMapperProfile>(); }); var mapper = config.CreateMapper(); Foo foo = new Foo { ID = 1, Name = "Tom" }; FooDto dto = mapper.Map<FooDto>(foo); } } }
2、在ASP.NET Core WebAPI中
public class AutoMapperProfile : Profile { public AutoMapperProfile() { CreateMap<Foo,FooDto>(); } }
public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddAutoMapper(typeof(AutoMapperProfile));//注册AutoMapper var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); }
[ApiController] [Route("[controller]")] public class testFroController : ControllerBase { private readonly IMapper mapper; public testFroController(IMapper mapper) { this.mapper = mapper; } [HttpGet(Name = "GetTestForFooDto")] public ActionResult<FooDto> Get() { Foo foo = new Foo { ID = 1, Name = "Tom" }; FooDto dto = mapper.Map<FooDto>(foo); return Ok(dto); } }