先说说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工具。

一、如何添加AutoMapper到项目中?

在vs中使用打开工具-库程序包管理器-程序包管理控制平台,输入“Install-Package AutoMapper”命令,就可以把AutoMapper添加到项目中了~

二、吃点栗子

栗子1(两个类型之间的映射)

Mapper.CreateMap<AddressDto, Address>();
AddressDto dto = new AddressDto
{
Country = "China",
City = "ShangHai",
Street = "JinZhong Street"
};
Address address = Mapper.Map<AddressDto,Address>(Dto);

栗子2(两个映射的对象有部分字段名称不一样)

AddressDto到Address的映射,AddressDto的字段CountryName要对应Address的字段Country:

Mapper.CreateMap<AddressDto, Address>(). ForMember(d => d.Country, opt => opt.MapFrom(s => s.CountryName));

栗子3(列表类型之间的映射)

源类型List<Address>,目标类型List<AddressDto>:

AutoMapper.Mapper.CreateMap< Address, AddressDto >();
var addressDtoList = AutoMapper.Mapper.Map<List< Address >, List< AddressDto >>( addressList);

栗子4(映射在增改查中的应用)

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的具体API文档吧!倘若在项目中真正要用的时候,我觉得还是应该对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简介的更多相关文章

  1. Asp.Net AutoMapper用法

    1.AutoMapper简介 用于两个对象映射,例如把Model的属性值赋值给View Model.传统写法会一个一个属性的映射很麻烦,使用AutoMapper两句代码搞定. 2.AutoMapper ...

  2. ASP.NET Core 中的对象映射之 AutoMapper

    目录 AutoMapper 简介 AutoMapper 使用 初始化 Profile设置 扁平化映射 集合映射 投影 条件映射 值转换 设置转换前后行为 配置验证及设置 反向映射 自定义转换器 自定义 ...

  3. 在ABP中灵活使用AutoMapper

    demo地址:ABP.WindowsService 该文章是系列文章 基于.NetCore和ABP框架如何让Windows服务执行Quartz定时作业 的其中一篇. AutoMapper简介 Auto ...

  4. AutoMapper使用

    1.安装 现在AutoMapper已经更新到5.0版本了,可查看 http://www.nuget.org/packages/AutoMapper/ 我环境是4.0的,nuget安装 http://w ...

  5. .NET的DTO映射工具AutoMapper

    .NET的DTO映射工具AutoMapper 原文:https://github.com/AutoMapper/AutoMapper/wiki/Getting-started 参考:http://ww ...

  6. AutoMapper 6.x 扩展方法

    简介 很多时候我们使用AutoMapper的时候,都需要进行一个配置才可以使用Mapper.Map<Source,Target>(entity);.如果不进行配置则会报错. 如果实体过多, ...

  7. AutoMapper 6.x 扩展

    简介 很多时候我们使用AutoMapper的时候,都需要进行一个配置才可以使用Mapper.Map<Source,Target>(entity);.如果不进行配置则会报错. 如果实体过多, ...

  8. 自己造轮子系列之OOM框架AutoMapper

    [前言] OOM框架想必大家在Web开发中是使用频率非常之高的,如果还不甚了解OOM框架,那么我们对OOM框架稍作讲解. OOM顾名思义,Object-Object-Mapping实体间相互转换.常见 ...

  9. .NET CORE 中使用AutoMapper进行对象映射

    简介 AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMappe ...

随机推荐

  1. anaconda新建环境

    安装tensorflow等如下: https://blog.csdn.net/Gransand/article/details/80713810 修改默认打开目录如下: https://blog.cs ...

  2. 解决vs code 内置终端,字体间隔过大问题。(linux centos7 ubuntu成功)

    去文件-首选项-设置里修改. "terminal.integrated.fontFamily": ""注意此处默认为空白,所以显示的就比较奇怪. 此处我改为&q ...

  3. 本地git安装完成之后,从远程git服务器上面下载代码。报错SSL certificate problem:self signed certificate in certificate chain。

    解决方案:打开git的控制端黑窗口,输入: git config --global http.sslVerify false 点击Entry之后,就会去掉git的ssl验证. 然后就可以正常的下载代码 ...

  4. BIO、NIO、AIO入门认识

    同步.异步.阻塞.非阻塞概念理解. 同步: 比如在执行某个逻辑业务,在没有得到结果之前一直处于等待阻塞状态,得到结果后才继续执行 异步: 比如在执行某个逻辑业务,在没有得到结果可以去干其他的事情,等待 ...

  5. dp转图论——cf1070A好题

    dp的状态转移很像一张有向图:每个状态为一个点,每中转移方案是一条有向边 本题要求是求出最小的数,那我们用状态[i,j]表示模i,数位和为j,那么从每个点出发的十条有向边代表[0,9]十个数 从每个状 ...

  6. 跨域问题The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by t

    withCredentials 属性 上面说到,CORS请求默认不发送Cookie和HTTP认证信息.如果要把Cookie发到服务器,一方面要服务器同意,指定Access-Control-Allow- ...

  7. shiro框架的组成和内部结构(下一篇为spring整合shiro)

    1.shiro简介 Apache Shiro是Java的一个安全框架.功能强大,使用简单的Java安全框架,它为开发人员提供一个直观而全面的认证,授权,加密及会话管理的解决方案. ​ 实际上,Shir ...

  8. JSOI 2008 魔兽地图

    题目描述 DotR (Defense of the Robots) Allstars是一个风靡全球的魔兽地图,他的规则简单与同样流行的地图DotA (Defense of the Ancients) ...

  9. react 16更新

    1.render新的返回类型 render方法支持两种新的返回类型:数组(由React元素组成)和字符串 2.错误处理 16之前,组件在运行期间如果执行出错,就会阻塞整个应用的渲染,这时候只能刷新页面 ...

  10. LANMP相关配置

    Linux Apache Mysql Postgresql 安装 yum -y install httpd yum -y install mysql mysql-server yum -y insta ...