• .NET Core 中AutoMapper使用配置


    1:AutoMapper说明

    对象转对象的一种映射器

    2:Core中如何配置AutoMapper

    1.NuGet安装AutoMapper.Extensions.Microsoft.DependencyInjection

    2.创建配置文件,并添加映射配置
    需要继承AutoMapper中的Profile,

    namespace Pckj.Test.Demo.Services
    {
        public class AutoMapperProfiles:Profile
        {
            public AutoMapperProfiles()
            {
                
        //构造函数中创建映射关系 
         CreateMap<Tsourse, TDes>().ReverseMap();  //Tsourse 原对象类型,TDes 目标对象类型  ReverseMap,可相互转换
            }
        }
    }
    

    3:在Startup启动类中的ConfigureServices方法中将服务添加到容器

        AutoMapperProfiles是上面步骤中定义的配置文件,具体代码如下:

      services.AddAutoMapper(typeof(AutoMapperProfiles));

    其他配置方式如下:

    public class Startup
        {
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="configuration"></param>
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
            /// <summary>
            /// 配置服务
            /// </summary>
            /// <param name="services"></param>
             public void ConfigureServices(IServiceCollection services)
             {
                  AutoMapper.MapperConfiguration config = new AutoMapper.MapperConfiguration(mce =>
                 {
                     mce.AddMaps(new string[] { "Pckj.Test.Demo.Services" });//添加程序集中包含的映射定义。寻找AutoMapper.Profile 【Pckj.Test.Demo.Services】程序集名称,也就是 AutoMapperProfiles所在的位置)
    
                   //mce.AddProfile(new AutoMapperProfiles()); 
                }); 
           var mapper = config.CreateMapper(); 
            services.AddSingleton<AutoMapper.IMapper>(mapper);
        }
     }

    使用示例:

     public class DemoService : IDemoService
        {
            /// <summary>
            /// 构造方法
            /// </summary>
            /// <param name="mapper"></param>
            public SupplierService(AutoMapper.IMapper mapper)
            {
                
                Mapper = mapper;
            }
          
            public AutoMapper.IMapper Mapper { get; set; }
         
    
              Mapper.Map<List<Tdes>>(List<Tsource>) ;//集合转换
              Mapper.Map<Tdes>(Tsource); //对象转换
     }
    

      

  • 相关阅读:
    2.5星|《无条件增长》:管理学常识+一些自己的管理案例
    3.5星|《壹棉壹世界》:棉花引发罪恶的黑奴贸易,影响美国南北战争
    只运行一个exe应用程序的使用案例
    WPF中使用WPFMediaKit视频截图案例
    Meta http-equiv属性详解
    层级数据模板 案例(HierarchicalDataTemplateWindow)
    ApplicationCommands 应用程序常见命令
    mvvm command的使用案例
    MatserDetail自动展开
    键盘焦点和逻辑焦点(Logic Focus与Keyboard Focus )
  • 原文地址:https://www.cnblogs.com/wu-peng/p/13815143.html
Copyright © 2020-2023  润新知