首页 > 其他 > 详细

map映射

时间:2019-06-10 17:04:39      阅读:87      评论:0      收藏:0      [点我收藏+]

 

using System;
using AutoMapper;
using System.Collections;
using System.Collections.Generic;

namespace Infrastructure
{
public static class AutoMapperExt
{
/// <summary>
/// 类型映射
/// </summary>
public static T MapTo<T>(this object obj)
{
if (obj == null) return default(T);

var config = new MapperConfiguration(cfg=>cfg.CreateMap(obj.GetType(),typeof(T)));
var mapper = config.CreateMapper();
return mapper.Map<T>(obj);
}

/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TDestination>(this IEnumerable source)
{
Type sourceType = source.GetType().GetGenericArguments()[0]; //获取枚举的成员类型
var config = new MapperConfiguration(cfg => cfg.CreateMap(sourceType, typeof(TDestination)));
var mapper = config.CreateMapper();

return mapper.Map<List<TDestination>>(source);
}

/// <summary>
/// 集合列表类型映射
/// </summary>
public static List<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
{
var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
var mapper = config.CreateMapper();

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;

var config = new MapperConfiguration(cfg => cfg.CreateMap(typeof(TSource), typeof(TDestination)));
var mapper = config.CreateMapper();
return mapper.Map<TDestination>(source);
}

}
}

map映射

原文:https://www.cnblogs.com/zhang-wenbin/p/10998239.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!