让AutoMapper使用变得简单

发布时间 2023-10-20 09:02:08作者: 永远1984

 

倘若在项目中真正要用的时候,我觉得还是应该对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>();