標籤: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