AutoMapper在项目中的应用
一、先说说DTO
DTO是个什么东东?
DTO(Data Transfer Object)就是数据传输对象,说白了就是一个对象,只不过里边全是数据而已。
为什么要用DTO?
1、DTO更注重数据,对领域对象进行合理封装,从而不会将领域对象的行为过分暴露给表现层。
2、DTO是面向UI的需求而设计的,而领域模型是面向业务而设计的。因此DTO更适合于和表现层的交互,通过DTO我们实现了表现层与领域Model之间的解耦,因此改动领域Model不会影响UI层。
3、DTO说白了就是数据而已,不包含任何的业务逻辑,属于瘦身型的对象,使用时可以根据不同的UI需求进行灵活的运用。
二、AutoMapper
现在我们既然知道了使用DTO的好处,那么我们肯定也想马上使用它,但是这里会牵扯一个问题:怎样实现DTO和领域Model之间的转换?
有两个思路,我们要么自己写转换代码,要么使用工具。不过就应用而言,我还是觉得用工具比较简单快捷,那就使用工具吧。其实这样的转换工具很多,不过我还是决定使用AutoMapper,因为它足够轻量级,而且也非常流行,国外的大牛们都使用它。使用AutoMapper可以很方便的实现DTO和领域Model之间的转换,它是一个强大的Object-Object Mapping工具。
1、如何添加AutoMapper到项目中?
在vs中使用打开工具-库程序包管理器-程序包管理控制平台,输入“Install-Package AutoMapper”命令,就可以把AutoMapper添加到项目中了。
2、案例源码
两个类型之间的映射
Mapper.CreateMap<AddressDto, Address>();
AddressDto dto = new AddressDto
{
Country = "China",
City = "ShangHai",
Street = "JinZhong Street"
};
Address address = Mapper.Map<AddressDto,Address>(Dto);
两个映射的对象有部分字段名称不一样
AddressDto到Address的映射,AddressDto的字段CountryName要对应Address的字段Country:
Mapper.CreateMap<AddressDto, Address>(). ForMember(d => d.Country, opt => opt.MapFrom(s => s.CountryName));
列表类型之间的映射
源类型List<Address>,目标类型List<AddressDto>:
AutoMapper.Mapper.CreateMap< Address, AddressDto >();
var addressDtoList = AutoMapper.Mapper.Map<List< Address >, List< AddressDto >>( addressList);
映射在增改查中的应用
public class ProductBll
{
Public IProductRepository productRepository{ set; get; }
public ProductDTO CreateProduct(ProductDTO productDTO)
{
Mapper.CreateMap<ProductDTO, Product>();
Product product = Mapper.Map<ProductDTO, Product>(productDTO);
productRepository.AddProduct(product);
return productDTO;
} public List<ProductDTO> GetProduct()
{
Mapper.CreateMap<Product, ProductDTO>();
List<ProductDTO> arr = new List<ProductDTO>();
productRepository.GetProduct().ForEach(i =>
{
arr.Add(Mapper.Map<Product, ProductDTO>(i));
});
return arr;
} public ProductDTO ModifyProduct(ProductDTO productDTO)
{
Mapper.CreateMap<ProductDTO, Product>();
Product product = Mapper.Map<ProductDTO, Product>(productDTO);
productRepository.ModifyProduct(product);
return productDTO;
}
}
三、让AutoMapper使用变得简单
倘若在项目中真正要用的时候,我觉得还是应该对AutoMapper的方法进行一些整理,最好能够封装一下,这里我通过扩展方法的形式将其封装为AutoMapperHelper,这样以后使用AutoMapper就变的SO EASY了。
using System.Collections;
using System.Collections.Generic;
using System.Data;
using AutoMapper;
namespace Infrastructure.Utility {
/// <summary>
/// AutoMapper扩展帮助类
/// </summary>
public static class AutoMapperHelper
{
/// <summary>
/// 类型映射
/// </summary>
public static T MapTo<T>(this object obj)
{
if (obj == null) return default(T);
Mapper.CreateMap(obj.GetType(), typeof(T));
return Mapper.Map<T>(obj);
}
/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
{
foreach (var first in source)
{
var type = first.GetType();
Mapper.CreateMap(type, typeof(TDestination));
break;
}
return Mapper.Map<List<TDestination>>(source);
}
/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
{
//IEnumerable<T> 类型需要创建元素的映射
Mapper.CreateMap<TSource, TDestination>();
return Mapper.Map<List<TDestination>>(source);
}
/// <summary>
/// 类型映射
/// </summary>
public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
where TSource : class
where TDestination : class
{
if (source == null) return destination;
Mapper.CreateMap<TSource, TDestination>();
return Mapper.Map(source, destination);
}
/// <summary>
/// DataReader映射
/// </summary>
public static IEnumerable<T> DataReaderMapTo<T>(this IDataReader reader)
{
Mapper.Reset();
Mapper.CreateMap<IDataReader, IEnumerable<T>>();
return Mapper.Map<IDataReader, IEnumerable<T>>(reader);
}
}
}
你可以像下面的例子这样使用:
//对象映射
ShipInfoModel shipInfoModel = ShipInfo.MapTo<ShipInfoModel>();
//列表映射
List< ShipInfoModel > shipInfoModellist = ShipInfoList.MapToList<ShipInfoModel>();
四、小结
在项目中多使用DTO实现表现层与领域Model的解耦,用AutoMapper来实现DTO与领域Model的相互转换,会让你体会到AutoMapper的便利。
参考链接:http://www.cnblogs.com/WeiGe/p/3835523.html
AutoMapper在项目中的应用的更多相关文章
- 记一次利用AutoMapper优化项目中数据层到业务层的数据传递过程。
目前项目中获取到DataSet数据后用下面这种方式复制数据. List<AgreementDoc> list = new List<AgreementDoc>(); ].Row ...
- AutoMapper之ABP项目中的使用介绍
最近在研究ABP项目,昨天写了Castle Windsor常用介绍以及其在ABP项目的应用介绍 欢迎各位拍砖,有关ABP的介绍请看阳光铭睿 博客 AutoMapper只要用来数据转换,在园里已经有很多 ...
- ABP项目中的使用AutoMapper
AutoMapper之ABP项目中的使用 最近在研究ABP项目,昨天写了Castle Windsor常用介绍以及其在ABP项目的应用介绍 欢迎各位拍砖,有关ABP的介绍请看阳光铭睿 博客 AutoMa ...
- 说说ABP项目中的AutoMapper,Castle Windsor(痛并快乐着)
这篇博客要说的东西跟ABP,AutoMapper和Castle Windsor都有关系,而且也是我在项目中遇到的问题,最终解决了,现在的感受就是“痛并快乐着”. 首先,这篇博客不是讲什么新的知识点,而 ...
- 在 ASP.NET Core 项目中使用 AutoMapper 进行实体映射
一.前言 在实际项目开发过程中,我们使用到的各种 ORM 组件都可以很便捷的将我们获取到的数据绑定到对应的 List<T> 集合中,因为我们最终想要在页面上展示的数据与数据库实体类之间可能 ...
- 转载 AutoMapper在C#中的有趣应用 https://www.cnblogs.com/lvlinlv/p/7344916.html
最近发现了一个比较有趣的东西 AutoMapper,主要将Model转换为DTO,DTO更注重数据,对领域对象进行合理封装,从而不会将领域对象的行为过分暴露给表现层. 先来看一点实例,两个类之间的映射 ...
- ABP module-zero +AdminLTE+Bootstrap Table+jQuery权限管理系统第十五节--缓存小结与ABP框架项目中 Redis Cache的实现
返回总目录:ABP+AdminLTE+Bootstrap Table权限管理系统一期 缓存 为什么要用缓存 为什么要用缓存呢,说缓存之前先说使用缓存的优点. 减少寄宿服务器的往返调用(round-tr ...
- AutoMapper实际项目运用
AutoMapper是对象到对象的映射工具.在完成映射规则之后,AutoMapper可以将源对象转换为目标对象. 配置AutoMapper映射规则 AutoMapper是基于约定的,因此在实用映射之前 ...
- AutoMapper在MVC中的运用01-配置、使用、单元测试、举例
MVC中,如果想在Domain Model和View Model之间建立映射,用AutoMapper是一个不错的选择.不仅如此,AutoMapper能在不同对象之间建立映射,比如string与int类 ...
随机推荐
- Spring IOC 容器源码分析 - 循环依赖的解决办法
1. 简介 本文,我们来看一下 Spring 是如何解决循环依赖问题的.在本篇文章中,我会首先向大家介绍一下什么是循环依赖.然后,进入源码分析阶段.为了更好的说明 Spring 解决循环依赖的办法,我 ...
- 关于各种算法以及好的blog的整理(持续更新)
一堆博客先扔着,等有空的时候再去看……好像没几个会的…… 以下都是待学习的算法 博弈论 https://www.cnblogs.com/cjyyb/p/9495131.html https://blo ...
- 预处理命令使用详解----#if、#endif、#undef、#ifdef、#else、#elif
预处理命令 在接触#if.#undef这类预处理指令前,大部分都都接触过#define.#include等预处理命令,通俗来讲预处理命令的作用就是在编译和链接之前,对源文件进行一些文本方面的操作,比如 ...
- CuratorFramework使用
CuratorFrameworkFramework是ZooKeeper Client更高的抽象API 自动连接管理: 1. 当ZooKeeper客户端内部出现异常, 将自动进行重连或重试, 该过程对外 ...
- nginx常用的超时配置说明
client_header_timeout 语法 client_header_timeout time默认值 60s上下文 http server说明 指定等待client发送一个请求头的超时时间(例 ...
- Python语法基础练习
- 基础I/O接口与操作
C语言中的文件接口 1 打开文件 FILE * fopen(const char * path,const char * mode) 参数:path:文件路径 mode:打开文件的方式 返回值:成功返 ...
- Redis笔记(1)数据结构与对象
1.前言 此系列博客记录redis设计与实现一书的笔记,提取书本中的知识点,省略相关说明,方便查阅. 2.基本数据结构 2.1 简单动态字符串SDS(simple dynamic string) 结构 ...
- 转:Intellij idea Version Control File Status Colors ( 版本控制文件状态颜色 )
https://blog.csdn.net/Bruce_Lee__/article/details/80261308 Added —— 添加 Added in not active changelis ...
- postgresql的启停和创建
一.启停方法 两种方法 1.直接运行postgres进程启动: 2.使用pg_ctl命令启动 postgres -D /home/osdba/pgdata & 二.停止数据库的三种模式 sm ...