自制AutoMapper實現DTO到持久層Entity的轉換

項目中經常涉及到頁面DTO更新,保存到數據庫的操作,這就必然牽扯到DTO和持久層對象的轉換,常見的第三方庫有:

java:dozer

.net: AutoMapper

看到AutoMapper已經許久沒更新了,而且項目中沒必要用這么大的東西,于是自己實現了一個簡易DTO到Entity的轉換器。

實現的功能

自定義的AutoMapper主要實現了如下幾點功能:

1.DTO字段忽略轉換

[AutoMapping(Ignore=true)]
public DateTime CreateTime { get; set; }

2.DTO字段和Entity的強制映射

[AutoMapping(EntityColumn="Sex")]
public string XingBie { get; set; }

3.默認DTO和Entity字段相同的,自動轉換

?

核心代碼:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;namespace ElegantWM.AutoMapper
{public class AutoMapper<T1,T2> where T1:new() where T2:new(){/// <summary>/// DTO 轉換為 Entity/// </summary>/// <typeparam name="T1">DTO</typeparam>/// <typeparam name="T2">Entity</typeparam>/// <param name="t1">Dto</param>/// <param name="t2">Entity</param>/// <returns></returns>public static T2 Convert(T1 t1, T2 t2){var dtoProperList = t1.GetType().GetProperties().Where(p => p.PropertyType.IsPublic == true).ToList();var entityProperList = t2.GetType().GetProperties().Where(p => p.PropertyType.IsPublic == true).ToList();foreach (System.Reflection.PropertyInfo pi in dtoProperList){string realName=pi.Name;//首先判斷列是否ignore?,是否含有Columnobject[] cusAttrs = pi.GetCustomAttributes(typeof(AutoMappingAttribute), true);if (cusAttrs.Length > 0){AutoMappingAttribute attr = cusAttrs[0] as AutoMappingAttribute;if (attr.Ignore)continue;if (!string.IsNullOrEmpty(attr.EntityColumn))realName = attr.EntityColumn;}var entityPi = entityProperList.Single(p => p.Name == realName);if (entityPi == null)continue;object value = pi.GetValue(t1, null);if (value == null)continue;entityPi.SetValue(t2, value, null);                }return t2;}}
}
案例

持久層Entity的定義如下:

public class Entity:IEntity{public Guid Id { get; set; }public string CreateUser { get; set; }public DateTime CreateTime { get; set; }public string ModifyUser { get; set; }public DateTime? ModifyTime { get; set; }[Timestamp]public Byte[] RowVersion { get; set; }}   public class WMS_User : Entity{public WMS_User() { }public string UserName { get; set; }public string NickName { get; set; }public string UserPwd { get; set; }public string Sex { get; set; }public string Phone { get; set; }public string Email { get; set; }public string QQ { get; set; }public string Address { get; set; }public string Remark { get; set; }public bool Disable { get; set; }public virtual ICollection<WMS_OrgUser> UserOrgIds { get; set; }}

頁面DTO定義如下:

public class UserDto{public UserDto() { }public Guid Id { get; set; }public string UserName { get; set; }public string NickName { get; set; }       public string UserPwd { get; set; }//強制字段映射[AutoMapping(EntityColumn="Sex")]public string XingBie { get; set; }public string Phone { get; set; }public string Email { get; set; }public string QQ { get; set; }public string Address { get; set; }public string Remark { get; set; }public bool Disable { get; set; }//忽略字段映射[AutoMapping(Ignore=true)]public DateTime CreateTime { get; set; }}    

使用AutoMapper,做轉換:

     [Action][Description("更新用戶")][HttpPut]public JsonResult Update(UserDto user){WMS_User userEntity = WMFactory.WMSUser.GetById(user.Id.ToString());
//*******看這里哦********userEntity = AutoMapper<UserDto, WMS_User>.Convert(user, userEntity);if (WMFactory.WMSUser.Update(userEntity))return Json(ResultMsg.Success("用戶信息更新成功!"));elsereturn Json(ResultMsg.Failure("用戶信息更新失敗,請您重試!"));}
寫在后面

自己實現,相對來說,自由度高了很多,你可以自己擴展方法,實現客制化的DTO轉Entity,讓AutoMapper更加適合自己的項目。

轉載于:https://www.cnblogs.com/qidian10/p/3173907.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉載,請注明出處:https://dhexx.cn/hk/18436.html

如若內容造成侵權/違法違規/事實不符,請聯系我的編程經驗分享網進行投訴反饋,一經查實,立即刪除!


相關文章:

  • spark常用RDD算子 - SortByKey
  • Nginx安裝及使用
  • 成功路很多,選對放心日賺幾百不是問題
  • spark常用RDD算子 - groupByKey
  • SpringBoot整合RabbitMQ消息中間件及多種設計模式
  • LCHub:ChatGPT4和低代碼來臨,程序員面臨下崗?
  • 運行Applet程序
  • Ubuntu12.04編譯Android4.0.1源碼全過程-----附wubi安裝ubuntu編譯android源碼硬盤空間不夠的問題解決...
  • Redis+SpringBoot整合
  • spark常用RDD算子 - cogroup
  • c# Xml反序列化示例
  • 《大話數據結構》圖的BFS和DFS
  • spark常用RDD算子 - 鍵值對關聯操作 subtractByKey, join,fullOuterJoin, rightOuterJoin, leftOuterJoin
  • 樹莓派_Linux串口編程_實現自發自收
  • 3.3FactoryMethod——工廠方法
  • Springboot筆記
  • spark常用RDD算子 - PairRDD的Action操作countByKey, collectAsMap
  • Spring與Hibernate、Mybatis整合
  • 學習ASP.NET MVC(五)——我的第一個ASP.NET MVC CURD頁面
  • SpringCloud學習之路
  • Spark Rdd分區 coalesce()方法和repartition()方法
  • 存儲引擎-存儲結構之二:頁
  • 配置開發支持高并發TCP連接的Linux應用程序全攻略
  • Spark RDD中的寬依賴和窄依賴
  • 學習java虛擬機
  • javascript 設置元素樣式 函數
  • 解決問題
  • Spark RDD Partitioner 分區機制解析
  • MySQL學習日記
  • 【不積跬步,無以致千里】關閉631端口cups打印服務和8009端口ajp
  • 阿里云服務器上安裝mysql的心路歷程(博友們進來看看哦)
  • Spark RDD分區 分區劃分器
  • SpringBoot發送郵件定時任務
  • 4.調個綠豆沙護眼色
  • MAC電腦之搭建lua開發環境
  • Spark RDD 緩存,持久化 cache(),persist()
  • 深入學習存儲過程
  • 指針的疑問
  • Scala 中的函數式編程基礎(二)
  • Git分支命令與項目實踐
  • Spark RDD checkpoint()機制
  • inline、block、inline-block的區別
  • PHP 提高PHP性能的編碼技巧以及性能優化
  • 瀏覽器的工作原理:新式網絡瀏覽器幕后揭秘
  • SPARK 編程入口 SparkContext,SparkSession
  • android使用Intent操作撥打號碼發送短信
  • Redis補充學習與主從復制和集群配置以及哨兵模式入門學習
  • java 獲取當前系統環境中的各種參數 System.getProperty()
  • jquery uploadify插件多文件上傳
  • git上傳時自動觸發Jenkins項目構建實戰