在上篇中我們通過創建一個類並繼承autoMapper的Profile類 public class Mappings : Profile { public Mappings() { CreateMap<UserDto, TbUser>(); } } 這樣做有一種弊端,就是當傳輸對象很多的時候,還需要手 ...
在上篇中我們通過創建一個類並繼承autoMapper的Profile類
public class Mappings : Profile { public Mappings() { CreateMap<UserDto, TbUser>(); } }
這樣做有一種弊端,就是當傳輸對象很多的時候,還需要手動一個個的配置映射關係,維護起來相對來說也比較麻煩。
封裝AutoMapper
創建AutoMapperExtension擴展類
/// <summary> /// AutoMapper擴展類 /// </summary> public static class AutoMapperExtension { /// <summary> /// 將源對象映射到目標對象 /// </summary> /// <typeparam name="T">實體類型</typeparam> /// <param name="obj">源對象</param> /// <returns>轉化之後的實體</returns> public static T MapTo<T>(this object obj) { if (obj == null) throw new Exception("異常"); var config = new MapperConfiguration(ctx => ctx.CreateMap(obj.GetType(), typeof(T))); var mapper = config.CreateMapper(); return mapper.Map<T>(obj); } /// <summary> /// 將源對象映射到目標對象 /// </summary> /// <typeparam name="T">實體類型</typeparam> /// <param name="dto">源對象</param> /// <param name="entity">目標對象</param> /// <returns>轉化之後的實體</returns> public static T Map<T>(object dto, T entity) { var config = new MapperConfiguration(ctx => ctx.CreateMap(dto.GetType(), typeof(T))); var mapper = config.CreateMapper(); var newModel = mapper.Map(dto, entity); return newModel; } }
修改業務層
去掉構造函數中IMapper註入
去掉啟動類Startup.cs中 services.AddAutoMapper(typeof(Mappings)) 方法
/// <summary> /// 添加用戶 /// </summary> /// <param name="dto">實體傳輸對象</param> /// <returns></returns> public int Add(UserDto dto) { //var info = _mapper.Map<UserDto, TbUser>(dto); var info = dto.MapTo<TbUser>(); info.AddTime = DateTime.Now; info.UserId = Guid.NewGuid().ToString("N"); //var user = new TbUser //{ // UserId = Guid.NewGuid().ToString("N"), // Email = dto.Email, // UserName = dto.UserName, // AddTime = DateTime.Now //}; _dbContext.Add(info); return _dbContext.SaveChanges(); } /// <summary> /// 編輯用戶信息 /// </summary> /// <param name="dto">實體傳輸對象</param> /// <returns></returns> public int Update(UserDto dto) { var user = _dbContext.TbUsers.Find(dto.UserId); if (user == null) throw new Exception("獲取用戶信息失敗"); //user.UserName = dto.UserName; //user.Email = dto.Email; AutoMapperExtension.Map(dto, user); return _dbContext.SaveChanges(); }
運行測試
跟封裝前一樣的效果