• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

Automapper 的ying'yong

开发技术 开发技术 5小时前 5次浏览

AutoMapper

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

结构图:

Automapper 的ying'yong

准备数据:

    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 的ying'yong
喜欢 (0)