AutoMapper 6.x 擴展
簡介
很多時候我們使用AutoMapper的時候,都需要進行一個配置才可以使用Mapper.Map
。如果不進行配置則會報錯。
如果實體過多,有時候會忘記是否有配置,只有運行的時候才會發現這個BUG。
源代碼地址- 源碼地址
- 測試案例地址
源代碼
該擴展基於AutoMapper 6.x
版本,因此需要從Nuget
下載相應的包。
該擴展對於Object
以及List
進行了兼容支持,因此MapTo
可以直接映射實體與泛型列表。
public static class Extensions /// /// /// /// /// } /// /// 類型
/// ///
///
{
///
///
///
/// 源對象
/// 目標對象
///
public static TDestination MapTo
{
return MapTo
}
///
///
/// 源對象
///
public static TDestination MapTo
{
return MapTo(source, new TDestination);
}
///
/// 源對象
/// 目標對象
///
private static TDestination MapTo
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
var sourceType = GetObjectType(source.GetType);
var destinationType = GetObjectType(typeof(TDestination));
try
{
var map = Mapper.Configuration.FindTypeMapFor(sourceType,destinationType);
if (map != null)
{
return Mapper.Map(source, destination);
}
var maps = Mapper.Configuration.GetAllTypeMaps;
Mapper.Initialize(config =>
{
foreach (var item in maps)
{
config.CreateMap(item.SourceType, item.DestinationType);
}
config.CreateMap(sourceType,destinationType);
});
catch (InvalidOperationException)
{
Mapper.Initialize(config =>
{
config.CreateMap(sourceType, destinationType);
});
}
return Mapper.Map(source, destination);
}
///
private static Type GetObjectType(Type source)
{
if (source.IsGenericType && typeof(IEnumerable).IsAssignableFrom(source))
{
var type = source.GetGenericArguments[0];
return GetObjectType(type);
}
return source;
}
}


※JVM總結之命令行工具
※python自定義異常
※通過history解決ajax不支持前進/後退/刷新
※ASP.NET Core Web API 最小化項目
※spark源碼分析之SparkContext初始化一
TAG:達人科技 |