.NetCore 使用AutoMapper

來源:互聯網
上載者:User

標籤:dep   映射   tin   source   添加引用   註冊   需要   for   code   

添加引用

AutoMapper

AutoMapper.Extensions.Microsoft.DependencyInjection

註冊服務
services.AddAutoMapper();
配置映射

services.AddAutoMapper(); 中DI了AutoMapper中需要用到的服務,其中包括AutoMapper的配置類 Profile

那麼怎麼來使用這個Profile,只需要自訂一個類 繼承 Profile 即可,在建構函式中配置下映射關係

 public class CustomMapping : Profile    {        public CustomMapping()        {                       CreateMap<Sys_UserLogininfo, LoginMsg>();            CreateMap<LoginMsg, Sys_UserLogininfo>();        }    }

這裡已經DI了CustomMapping,所以執行個體化了,建構函式自然也被執行過了,不需要再去DI CustomMapping類,在AutoMapper.Extensions.Microsoft.DependencyInjection中的

AddAutoMapper已經做了這些事情,這其中包括 IMapper 介面

在需要用的AutoMapper的地方通過建構函式注入下IMapper對象即可

如建構函式注入
        IMapper _mapper;        public UserController(IMapper mapper)        {            _mapper = mapper;        }
   _mapper.Map<LoginMsg, Sys_UserLogininfo>(loginMsg);

額外說明:在使用AutoMapper過程中如果類中欄位不一致需要實現映射怎麼處理

 CreateMap<Sys_UserLogininfo, LoginMsg>().ForMember(c=>c.UserName,x=>x.MapFrom(k=>k.Use_Use));

映射 MapFrom 來自哪裡的欄位 到 ForMember 哪個欄位

注意 

CreateMap<Source,Destination>(); 來源->目標

 

.NetCore 使用AutoMapper

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.