自制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 ...
随机推荐
- JAVA 长整型转换为IP地址的方法
JAVA 长整型转换为IP地址的方法 代码例如以下: /** * 整型解析为IP地址 * @param num * @return */ public static String int2iP(Lon ...
- SSAS系列——【01】准备知识
原文:SSAS系列--[01]准备知识 关于SQL Server 产品,我从2004年就开始使用了,SQL Server 2K,2K5,2K8,到如今已经准6年了,说来惭愧,这六年来所涉及的内容都是在 ...
- 基于Http替补新闻WebService数据交换
该系统的工作之间的相互作用.随着信息化建设的发展,而业界SOA了解并带来低TOC(总拥有成本)其他优势.越来越多的高层次的信息使用者关注. 这里暂且不提SOA这种架构规划.在系统间集成协议简单的讨论. ...
- php中soap应用
原文:php中soap应用 SOAP:简单对象访问协议 (SOAP:Simple Object Access Protocol) 简单对象访问协议(SOAP)是一种轻量的.简单的.基于 XML 的协议 ...
- 从源代码上分析ListView的addHeaderView和setAdapter的调用顺序
ListView想要加入headerview的话,就要通过addHeaderView这种方法,然后想要为ListView设置数据的话,就要调用setAdapter方法了.可是,在调用addHeader ...
- java设计模式之单例模式(七种方法)
单例模式:个人认为这个是最简单的一种设计模式,而且也是在我们开发中最常用的一个设计模式. 单例模式的意思就是只有一个实例.单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例.这个 ...
- SQL点滴16—SQL分页语句总结
原文:SQL点滴16-SQL分页语句总结 今天对分页语句做一个简单的总结,他们大同小异的,只要理解其中一个其他的就很好理解了. 使用top选项 *from Orders orderid from Or ...
- Windows在结构FTPserver
同Windows8 案件,结构介绍 FTPserver脚步: 1.为Windows开启FTP功能:控制面板->程序->启用或关闭Windows功能.将下图所看到的的复选框选中 waterm ...
- leetcode第29题--Substring with Concatenation of All Words
problem: You are given a string, S, and a list of words, L, that are all of the same length. Find al ...
- office编程必不可少
原文:office编程必不可少 [转] 1. 微软官方实例: 段落.表格.图表 HOW TO:利用 Visual C# .NET 使 Word 自动新建文档 2. 学习资源 (1)Word in th ...