使用AutoMapper

发布时间 2023-12-04 11:37:19作者: 坤机嘎嘎嘎

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);

        }
    }
}
在控制台中使用AutoMapper

2、在ASP.NET Core WebAPI中

public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile() 
        {
            CreateMap<Foo,FooDto>();
        }
    }
创建AutoMapperConfig.cs文件,继承自Profile
 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();
        }
在Main中注册AutoMapper
 [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);
        }
    }
在Controller中使用AutoMapper