【AutoMapper】实体转实体映射
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可以很方便的实现实体和实体之间的转换,它是一个强大的对象映射(Object-Object Mapping)工具。
一,如何添加AutoMapper到项目中?
在vs中使用打开工具 - 库程序包管理器 - 程序包管理控制平台,输入“Install-Package AutoMapper”命令,就可以把AutoMapper添加到项目中了〜
二,举个栗子
栗子1:两个实体之间的映射
Mapper.CreateMap <Test1,Test2>();
Test1 test1 = new Test1 {Id = 1,Name =“张三”,Date = DateTime.Now};
Test2 test2 = Mapper.Map(test1);
栗子2:两个实体不同字段之间的映射
Mapper.CreateMap <Test1,Test2>().ForMember(d => d.Name121,opt => opt.MapFrom(s => s.Name));
栗子3:泛型之间的映射
Mapper.CreateMap <Test1,Test2>();
var testList = Mapper.Map <List,List >(testList);
三,扩展映射方法使映射变得更简单
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);
}
}
}
这样的话,你就可以这样使用了
var testDto = test.MapTo <Test2>();
var testDtoList = testList.MapTo <Test2>();

浙公网安备 33010602011771号