自制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 ...
随机推荐
- asp.net 获得客户端 mac 地址
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- Xutils呼叫流源代码文件下载方法
//我主要是好奇Xutils哪里回调onLoading(),查找等了很久也没找到,果然easy查找只是把它写下来 前言: 1.代码摘要只有主线,提供一般流程 2.为了易于理解,码变量名,而是类名的驼峰 ...
- 一步一步写算法(之prim算法 上)
原文:一步一步写算法(之prim算法 上) [ 声明:版权所有,欢迎转载,请勿用于商业用途. 联系信箱:feixiaoxing @163.com] 前面我们讨论了图的创建.添加.删除和保存等问题.今 ...
- AngularJS + Node.js + MongoDB开发
AngularJS + Node.js + MongoDB开发的基于位置的通讯录(by vczero) 一.闲扯 有一天班长说了,同学们希望我开发一个可以共享位置的通讯录,于是自己简单设计了下功能.包 ...
- oracle获取字符串长度函数length()和hengthb()
原文:oracle获取字符串长度函数length()和hengthb() lengthb(string)计算string所占的字节长度:返回字符串的长度,单位是字节 length(string)计算s ...
- jQuery圆形统计图实战开发
今天我给大家介绍一款圆形统计图circliful,它基于HTML5的画布和jQuery,无需使用图像轻松实现圆形统计图,而且有很多属性设置,使用起来非常方便. 首先我们需要将jquery库文件和jqu ...
- Visual Studio 2010 单元测试--运行测试并查看代码覆盖率
原文:Visual Studio 2010 单元测试--运行测试并查看代码覆盖率 运行测试并查看代码覆盖率对程序集中的代码运行测试时,可以通过收集代码覆盖率数据来查看正在测试的项目代码部分. 运行测试 ...
- postal邮件发送(一):基本配置
前言 源码:https://github.com/andrewdavey/postal 文档:http://aboutcode.net/postal/ postal最大好处就是再也不用拼接html发送 ...
- 33、Python.Unix和Linux系统管理指南.(美)基弗特
- linux 启动oracle报cannot restore segment prot after reloc: Permission denied
error while loading shared libraries: $ORACLE_HOME/lib/libnnz10.so: cannot restore segment prot afte ...