Automapper 的ying'yong

AutoMapper net core

1.入门例子

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 void Map()
{
    var config = new MapperConfiguration(cfg => cfg.CreateMap<Foo, FooDto>());

    var mapper = config.CreateMapper();

    Foo foo = new Foo { ID = 1, Name = "Tom" };

    FooDto dto = mapper.Map<FooDto>(foo);
}

2.在net core的应用

net framework 引入包: AutoMapper

net core 引入专属包:AutoMapper.Extensions.Microsoft.DependencyInjection

结构图:

准备数据:

    public class Foo
    {
        public int ID { get; set; }

        public string Name { get; set; }
        public int Price { get; set; }
    }
    
    public class FooDto
    {
        public int ID { get; set; }

        public string Name { get; set; }

        public int NewPrice { get; set; }

    }

    public class FooProfile : Profile
    {
        public FooProfile()
        {
            //从 src 投影到 dest
            //destinationMember:投影对象
            //memberOptions:(opt:原始对象).MapFrom:使用自定义表达式映射目标成员。用于LINQ投影(ProjectTo)。
            CreateMap<Foo, FooDto>()
                .ForMember(dest => dest.NewPrice, opt => opt.MapFrom(src => src.Price + 1));
        }
    }

在Startup.cs 注入:

        //扫描profile文件
		//如果只扫描一个FooProfile,使用 services.AddAutoMapper(FooProfile);
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

Controller 两种方式:

    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private readonly IMapper _mapper;
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger, IMapper mapper)
        {
            _logger = logger;
            _mapper = mapper;
        }

        [HttpGet]
        public JsonResult Get()
        {
            Foo foo = new Foo { ID = 1, Name = "Tom", Price = 1 };
            //1.Profile 注入
            FooDto dto = _mapper.Map<FooDto>(foo);
            //2.不注入
            //var config = new MapperConfiguration(cfg => cfg.CreateMap<Foo, FooDto>().ForMember(dest => dest.NewPrice, opt => opt.MapFrom(src => src.Price + 2)));
            //var mapper2 = config.CreateMapper();
            //FooDto dto = mapper2.Map<FooDto>(foo);

            return new JsonResult(dto);
        }
    }

3.参考

丹枫无迹:【C#】AutoMapper 使用手册

automapper net

MapperModel\DefaultMapper.cs

posted @ 2021-06-10 23:11  【唐】三三  阅读(83)  评论(0编辑  收藏  举报