自制AutoMapper实现DTO到持久层Entity的转换
自制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更加适合自己的项目。
文章部分内容可能摘自网络,如果侵犯您的权益,请及时联系我,谢谢.

自制AutoMapper实现DTO到持久层Entity的转换的更多相关文章
- (转)自制AutoMapper实现DTO到持久层Entity的转换
原文地址:http://www.cnblogs.com/qidian10/p/3173907.html 项目中经常涉及到页面DTO更新,保存到数据库的操作,这就必然牵扯到DTO和持久层对象的转换,常见 ...
- UWP开发之ORM实践:如何使用Entity Framework Core做SQLite数据持久层?
选择SQLite的理由 在做UWP开发的时候我们首选的本地数据库一般都是Sqlite,我以前也不知道为啥?后来仔细研究了一下也是有原因的: 1,微软做的UWP应用大部分也是用Sqlite.或者说是微软 ...
- CJCMS系列--持久层对MangoDB的支持
持久层添加对MangoDB数据库的支持 using System; using System.Collections.Generic; using System.Linq; using System. ...
- Restful.Data v1.0 - 轻量级数据持久层组件, 正式开源发布了
经过几个星期的优化调整,今天 Restful.Data 正式开源发布. 源码地址:https://github.com/linli8/Restful 今天不写那么多废话了,还是重新介绍一下 Restf ...
- .NET平台下,关于数据持久层框架
在.NET平台下,关于数据持久层框架非常多,本文主要对如下几种做简要的介绍并推荐一些学习的资源: 1.NHibernate 2.NBear 3.Castle ActiveRecord 4.iBATIS ...
- .NET开源项目介绍及资源推荐:数据持久层
在.NET平台下,关于数据持久层框架非常多,本文主要对如下几种做简要的介绍并推荐一些学习的资源: 1.NHibernate 2.NBear 3.Castle ActiveRecord 4.iBATIS ...
- 一种好的持久层开发方法——建立BaseDao和BaseDaoImpl
使用hibernate开发持久层时,我们会发现:虽然entity类的含义和需求不同,其对应的Dao层类对应的方法也是不同的.但是有许多方法操作确实相同的.比如实体的增加,删除,修改更新,以及许多常用的 ...
- [置顶] 数据持久层(DAO)常用功能–通用API的实现
在Web开发中,一般都分3层. Controller/Action 控制层, Service/Business 服务层/业务逻辑层, Dao 数据访问层/数据持久层. 在学习和工作的实践过程中,我发现 ...
- JPA规范及其它持久层框架
JPA是一种规范,而hibernate是JPA的一种实现 JPA全称为Java Persistence API ,Java持久化API是Sun公司在Java EE 5规范中提出的Java持久化接口.J ...
随机推荐
- 如何将经纬度利用Google Map API显示C# VS2005 Sample Code
原文 如何将经纬度利用Google Map API显示C# VS2005 Sample Code 日前写了一篇如何用GPS抓取目前所在,并回传至资料库储存,这篇将会利用这些回报的资料,将它显示在地图上 ...
- C# 获取与解析枚举类型的 DescriptionAttribute
原文:C# 获取与解析枚举类型的 DescriptionAttribute System.ComponentModel.DescriptionAttribute 这个 Attribute,经常被用来为 ...
- linux下C语言中的flock函数使用方法 .
表头文件 #include<sys/file.h> 定义函数 int flock(int fd,int operation); 函数说明 flock()会依參数operation所指 ...
- HBuilder CSS 自定义代码块
=begin 本文档是CSS代码块的编辑文件.注意不要把其他语言的设置放到css里来. HBuilder可使用ruby脚本来编辑代码块和增强操作命令. 1.编辑代码块 如果要新增一个代码块,复制如下一 ...
- JQuery Smart UI
JQuery Smart UI 个人开发的一套使用htm+js的开发框架 SmartUI2.0后续声明 摘要: 感谢很多朋友关注,因为今年一直在另外一个公司做顾问,网络环境管制相当严格,所以一直没有更 ...
- 使用Windows2003创建FTP服务器 - 进阶者系列 - 学习者系列文章
现在有不少的FTP建设软件,比如Server-U软件.不过本文只介绍使用Windows2003来创建FTP服务器. 1. 打开控制面板的添加删除程序. 2. 打开 添加删除Windows组件 3. ...
- lsof基本使用
当你想在计算机上启动一个服务,电脑已经建议"port already in use",此时,可以使用lsof命令查看占用端口的进程(lsof -i:port). lsof这是LiS ...
- 探索Android该Parcel机制上
一.先从Serialize说起 我们都知道JAVA中的Serialize机制.译成串行化.序列化……,其作用是能将数据对象存入字节流其中,在须要时又一次生成对象.主要应用是利用外部存储设备保存对象状态 ...
- .Net中批量添加数据的几种实现方法比较
在.Net中经常会遇到批量添加数据,如将Excel中的数据导入数据库,直接在DataGridView控件中添加数据再保存到数据库等等. 方法一:一条一条循环添加 通常我们的第一反应是采用for或for ...
- css Cursor:url()自定义鼠标指针样式为图片
css自定义鼠标指针样式为图片Cursor:url()的使用,今天在项目中,要用到自定义鼠标样式,格式: css:{cursor:url('绝对路径的图片(格式:cur,ico)'),-moz-zoo ...