.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); //對象轉換
 }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM