步驟1:項(xiàng)目引用
AutoMapper
AutoMapper.Extensions.Microsoft.DependencyInjection
步驟2:建立文件 DevProCommonFile
IProfile:是一個(gè)空接口,主要用來動(dòng)態(tài)加載文件時(shí)查找相關(guān)文件,也就時(shí)說DevProCommonFile這種文件可以建立多個(gè),只要繼承Profile, IProfile就會被框架加入using AutoMapper;using Dev.WooNet.Model.DevDTO;using Dev.WooNet.Model.Models;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Dev.WooNet.AutoMapper.ProFiles{ /// <summary> /// 公共映射文件 /// </summary> public class DevProCommonFile : Profile, IProfile { public DevProCommonFile() { CreateMap<DepartData, DevDepartment>(); //.ForMember(a => a.ContId, opt => opt.Ignore()) //.ForMember(a => a.CreateUserId, opt => opt.Ignore()) //.ForMember(a => a.CreateDateTime, opt => opt.Ignore()) //.ForMember(a => a.ModifyUserId, opt => opt.Ignore()) //.ForMember(a => a.ModifyDateTime, opt => opt.Ignore()); } }}
步驟3:設(shè)置加載文件規(guī)則
建立Mappings 定一個(gè)擴(kuò)展方法AddDevMapperFiles
using AutoMapper;using Microsoft.Extensions.DependencyInjection;using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Text;using System.Threading.Tasks;namespace Dev.WooNet.AutoMapper.Extend{ public static class Mappings { /// <summary> ///映射文件 /// </summary> /// <param name="service"></param> public static void AddDevMapperFiles(this IServiceCollection service) { var allType = Assembly .GetEntryAssembly()//獲取默認(rèn)程序集 .GetReferencedAssemblies()//獲取所有引用程序集 .Select(Assembly.Load) .SelectMany(y => y.DefinedTypes) .Where(type => typeof(IProfile).GetTypeInfo().IsAssignableFrom(type.AsType())); service.AddAutoMapper(allType.ToArray()); } }}
步驟4:Startup 的ConfigureServices進(jìn)行注冊
services.AddDevMapperFiles();(上面擴(kuò)展方法)
步驟5:應(yīng)用 在控制器注入 IMapper
private IMapper _IMapper { get; set; }
然后 var deptinfo = _IMapper.Map<DevDepartment>(departData);
這樣就完成了AutoMapper使用
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點(diǎn)擊舉報(bào)。