.NET CORE 中使用AutoMapper进行对象映射


简介

AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMapper uses a convention-based matching algorithm to match up source to destination values. AutoMapper is geared towards model projection scenarios to flatten complex object models to DTOs and other simple objects, whose design is better suited for serialization, communication, messaging, or simply an anti-corruption layer between the domain and application layer.

官网:http://automapper.org/

文档:https://automapper.readthedocs.io/en/latest/index.html

GitHub:https://github.com/AutoMapper/AutoMapper/blob/master/docs/index.rst

平台支持:

  • .NET 4.6.1+
  • .NET Standard 2.0+ https://docs.microsoft.com/en-us/dotnet/standard/net-standard

使用

Nuget安装

AutoMapper       
AutoMapper.Extensions.Microsoft.DependencyInjection  //依赖注入AutoMapper,需要下载该包。

在Startup中添加AutoMapper

复制代码
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    //添加对AutoMapper的支持
    services.AddAutoMapper();
}
复制代码

创建AutoMapper映射规则

复制代码
public class AutoMapperConfigs:Profile
{
    //添加你的实体映射关系.
    public AutoMapperConfigs()
    {
        CreateMap<DBPoundSheet, PoundSheetViewModel>();
        CreateMap<PoundSheetViewModel, DBPoundSheet>();
    }
}
复制代码

在构造函数中注入你的IMapper

复制代码
IMapper _mapper;

public PoundListController(IMapper mapper)
{
    _mapper = mapper;
}
复制代码

单个对象转换

//typeof(model)="PoundSheetViewModel"
DBPoundSheet dBPoundSheet = _mapper.Map<DBPoundSheet>(model);

集合对象转换


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM