自制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?,是否含有Column
object[] 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("用户信息更新成功!"));
else
return Json(ResultMsg.Failure("用户信息更新失败,请您重试!"));
}
写在后面

自己实现,相对来说,自由度高了很多,你可以自己扩展方法,实现客制化的DTO转Entity,让AutoMapper更加适合自己的项目。

如果您认可我的工作,并且觉得本文对您有所帮助,可以通过支付宝或转发文章的方式资助我们,我们愿意接受来自各方面的捐赠。再次感谢您对开源事业的赞助和支持!
文章部分内容可能摘自网络,如果侵犯您的权益,请及时联系我,谢谢.
作者:JackChain
 
分类: .Net软件架构

自制AutoMapper实现DTO到持久层Entity的转换的更多相关文章

  1. (转)自制AutoMapper实现DTO到持久层Entity的转换

    原文地址:http://www.cnblogs.com/qidian10/p/3173907.html 项目中经常涉及到页面DTO更新,保存到数据库的操作,这就必然牵扯到DTO和持久层对象的转换,常见 ...

  2. UWP开发之ORM实践:如何使用Entity Framework Core做SQLite数据持久层?

    选择SQLite的理由 在做UWP开发的时候我们首选的本地数据库一般都是Sqlite,我以前也不知道为啥?后来仔细研究了一下也是有原因的: 1,微软做的UWP应用大部分也是用Sqlite.或者说是微软 ...

  3. CJCMS系列--持久层对MangoDB的支持

    持久层添加对MangoDB数据库的支持 using System; using System.Collections.Generic; using System.Linq; using System. ...

  4. Restful.Data v1.0 - 轻量级数据持久层组件, 正式开源发布了

    经过几个星期的优化调整,今天 Restful.Data 正式开源发布. 源码地址:https://github.com/linli8/Restful 今天不写那么多废话了,还是重新介绍一下 Restf ...

  5. .NET平台下,关于数据持久层框架

    在.NET平台下,关于数据持久层框架非常多,本文主要对如下几种做简要的介绍并推荐一些学习的资源: 1.NHibernate 2.NBear 3.Castle ActiveRecord 4.iBATIS ...

  6. .NET开源项目介绍及资源推荐:数据持久层

    在.NET平台下,关于数据持久层框架非常多,本文主要对如下几种做简要的介绍并推荐一些学习的资源: 1.NHibernate 2.NBear 3.Castle ActiveRecord 4.iBATIS ...

  7. 一种好的持久层开发方法——建立BaseDao和BaseDaoImpl

    使用hibernate开发持久层时,我们会发现:虽然entity类的含义和需求不同,其对应的Dao层类对应的方法也是不同的.但是有许多方法操作确实相同的.比如实体的增加,删除,修改更新,以及许多常用的 ...

  8. [置顶] 数据持久层(DAO)常用功能–通用API的实现

    在Web开发中,一般都分3层. Controller/Action 控制层, Service/Business 服务层/业务逻辑层, Dao 数据访问层/数据持久层. 在学习和工作的实践过程中,我发现 ...

  9. JPA规范及其它持久层框架

    JPA是一种规范,而hibernate是JPA的一种实现 JPA全称为Java Persistence API ,Java持久化API是Sun公司在Java EE 5规范中提出的Java持久化接口.J ...

随机推荐

  1. ssh 自动登录

    工作中经常会有这样的需求场景,因为要在其它电脑上做操作, 需要从PC A ssh 到 PC B,PC A 可能是自己的工作机,PC B 可能是服务器.一般会使用 SSH 登录到 server 上再进行 ...

  2. R - 变化plot字形,嵌入字体以pdf

    近期使用R绘图遇到两个问题 1. 使用不同的字体 2. 保存 plot 至 pdf 当字体嵌入pdf (embed the font) 使用extrafont和Ghostscript能够解决这两个问题 ...

  3. 第1章3节《MonkeyRunner源码剖析》概述:架构(原创)

    天地会珠海分舵注:本来这一系列是准备出一本书的,详情请见早前博文“寻求合作伙伴编写<深入理解 MonkeyRunner>书籍“.但因为诸多原因,没有如愿.所以这里把草稿分享出来,所以错误在 ...

  4. AngularJS + Node.js + MongoDB开发

    AngularJS + Node.js + MongoDB开发的基于位置的通讯录(by vczero) 一.闲扯 有一天班长说了,同学们希望我开发一个可以共享位置的通讯录,于是自己简单设计了下功能.包 ...

  5. win7下的PHP+IIS配置,找不到php5isapi.dll的问题,版本5.4.9

    原文:win7下的PHP+IIS配置,找不到php5isapi.dll的问题,版本5.4.9 问题:PHP新手配置,在官网上下载的压缩包.按网上的找的教程配置IIS时发现,在解压包里找不到php5is ...

  6. html5 Canvas画图3:1px线条模糊问题

    点击查看原文地址: html5 Canvas画图3:1px线条模糊问题 本文属于<html5 Canvas画图系列教程> 接上一篇canvas画线条教程 上次我们讲到,canvas有时候会 ...

  7. js实现是倒计时功能

    工作中经常用到倒计时的功能,最近在整理之前做的项目的时候,发现自己写过一个倒计时的功能的效果,这里和大家分享下!实现这个功能是用原生js写的,不需要加载额外的库文件!功能比较简单,但是可以在此基础上扩 ...

  8. Routing(路由) & Multiple Views(多个视图) step 7

    Routing(路由) & Multiple Views(多个视图) step 7 1.切换分支到step7,并启动项目 git checkout step-7 npm start 2.需求: ...

  9. HBase MVCC 代码阅读(一)

    MultiVersionConcurrencyControl.java,版本 0.94.1 MultiVersionConsistencyControl 管理 memstore 中的读写一致性.该类实 ...

  10. JAVA修饰符类型(转帖)

    JAVA修饰符类型(public,protected,private,friendly) public的类.类属变量及方法,包内及包外的任何类均可以访问:protected的类.类属变量及方法,包内的 ...