倘若在项目中真正要用的时候,我觉得还是应该对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);
}
}
}
你可以像下面的例子这样使用:
标签:Mapper,return,映射,source,static,简单,AutoMapper,变得 From: https://www.cnblogs.com/wgy1984/p/17776228.html//对象映射
ShipInfoModel shipInfoModel = ShipInfo.MapTo<ShipInfoModel>();
//列表映射
List< ShipInfoModel > shipInfoModellist = ShipInfoList.MapToList<ShipInfoModel>();