NetCore AutoMapper的封装
需要引用AutoMapper的Nuget包
如果需要忽略某个字段就在字段上面打标签如下:
[IgnoreMap]
public string IgnoreValue { get; set; }
/// <summary>
/// 对象映射
/// </summary>
public static class Extensions
{
/// <summary>
/// 同步锁
/// </summary>
private static readonly object Sync = new object(); /// <summary>
/// 将源对象映射到目标对象
/// </summary>
/// <typeparam name="TSource">源类型</typeparam>
/// <typeparam name="TDestination">目标类型</typeparam>
/// <param name="source">源对象</param>
/// <param name="destination">目标对象</param>
public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
{
return MapTo<TDestination>(source, destination);
} /// <summary>
/// 将源对象映射到目标对象
/// </summary>
/// <typeparam name="TDestination">目标类型</typeparam>
/// <param name="source">源对象</param>
public static TDestination MapTo<TDestination>(this object source) where TDestination : new()
{
return MapTo(source, new TDestination());
} /// <summary>
/// 将源对象映射到目标对象
/// </summary>
private static TDestination MapTo<TDestination>(object source, TDestination destination)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
var sourceType = GetType(source);
var destinationType = GetType(destination);
var map = GetMap(sourceType, destinationType);
if (map != null)
return Mapper.Map(source, destination);
lock (Sync)
{
map = GetMap(sourceType, destinationType);
if (map != null)
return Mapper.Map(source, destination);
InitMaps(sourceType, destinationType);
}
return Mapper.Map(source, destination);
} /// <summary>
/// 获取类型
/// </summary>
private static Type GetType(object obj)
{
var type = obj.GetType();
if ((obj is System.Collections.IEnumerable) == false)
return type;
if (type.IsArray)
return type.GetElementType();
var genericArgumentsTypes = type.GetTypeInfo().GetGenericArguments();
if (genericArgumentsTypes == null || genericArgumentsTypes.Length == 0)
throw new ArgumentException("泛型类型参数不能为空");
return genericArgumentsTypes[0];
} /// <summary>
/// 获取映射配置
/// </summary>
private static TypeMap GetMap(Type sourceType, Type destinationType)
{
try
{
return Mapper.Configuration.FindTypeMapFor(sourceType, destinationType);
}
catch (InvalidOperationException)
{
lock (Sync)
{
try
{
return Mapper.Configuration.FindTypeMapFor(sourceType, destinationType);
}
catch (InvalidOperationException)
{
InitMaps(sourceType, destinationType);
}
return Mapper.Configuration.FindTypeMapFor(sourceType, destinationType);
}
}
} /// <summary>
/// 初始化映射配置
/// </summary>
private static void InitMaps(Type sourceType, Type destinationType)
{
try
{
var maps = Mapper.Configuration.GetAllTypeMaps();
Mapper.Initialize(config => {
ClearConfig();
foreach (var item in maps)
config.CreateMap(item.SourceType, item.DestinationType);
config.CreateMap(sourceType, destinationType);
});
}
catch (InvalidOperationException)
{
Mapper.Initialize(config => {
config.CreateMap(sourceType, destinationType);
});
}
} /// <summary>
/// 清空配置
/// </summary>
private static void ClearConfig()
{
var typeMapper = typeof(Mapper).GetTypeInfo();
var configuration = typeMapper.GetDeclaredField("_configuration");
configuration.SetValue(null, null, BindingFlags.Static, null, CultureInfo.CurrentCulture);
} /// <summary>
/// 将源集合映射到目标集合
/// </summary>
/// <typeparam name="TDestination">目标元素类型,范例:Sample,不要加List</typeparam>
/// <param name="source">源集合</param>
public static List<TDestination> MapToList<TDestination>(this System.Collections.IEnumerable source)
{
return MapTo<List<TDestination>>(source);
}
}
NetCore AutoMapper的封装的更多相关文章
- netcore 2.2 封装 AutoMapper
在上篇中我们通过创建一个类并继承autoMapper的Profile类 public class Mappings : Profile { public Mappings() { CreateMap& ...
- NetCore+AutoMapper多个对象映射到一个Dto对象
目录 一. 定义源映射类和被映射类DTO二.注入AutoMapper三.配置映射四.写测试 一.定义源映射对象 为了体现AutoMapper映射特性,在SocialAttribute中的Name属性没 ...
- 【NetCore】RabbitMQ 封装
RabbitMQ 封装 代码 https://gitee.com/wosperry/wosperry-rabbit-mqtest/tree/master 参考Abp事件总线的用法,对拷贝的Demo进行 ...
- AutoMapper 使用总结
初识AutoMapper 在开始本篇文章之前,先来思考一个问题:一个项目分多层架构,如显示层.业务逻辑层.服务层.数据访问层.层与层访问需要数据载体,也就是类.如果多层通用一个类,一则会暴露出每层的字 ...
- 初识AutoMapper
在开始本篇文章之前,先来思考一个问题:一个项目分多层架构,如显示层.业务逻辑层.服务层.数据访问层.层与层访问需要数据载体,也就是类.如果多层通用一个类,一则会暴露出每层的字段,二者会使类字段很多,而 ...
- AutoMapper 使用总结1
初识AutoMapper 在开始本篇文章之前,先来思考一个问题:一个项目分多层架构,如显示层.业务逻辑层.服务层.数据访问层.层与层访问需要数据载体,也就是类.如果多层通用一个类,一则会暴露出每层的字 ...
- AutoMapper在asp.netcore中的使用
# AutoMapper在asp.netcore中的使用 automapper 是.net 项目中针对模型之间转换映射的一个很好用的工具,不仅提高了开发的效率还使代码更加简洁,当然也是开源的,htt ...
- c# AutoMapper 使用方式和再封装
安装方式:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可. 我从网上找了一些资料, 参考网址:http://blog.csdn.net/csethcrm/a ...
- Python3 与 C# 面向对象之~继承与多态 Python3 与 C# 面向对象之~封装 Python3 与 NetCore 基础语法对比(Function专栏) [C#]C#时间日期操作 [C#]C#中字符串的操作 [ASP.NET]NTKO插件使用常见问题 我对C#的认知。
Python3 与 C# 面向对象之-继承与多态 文章汇总:https://www.cnblogs.com/dotnetcrazy/p/9160514.html 目录: 2.继承 ¶ 2.1.单继 ...
随机推荐
- C#实现下载的几种方式举例
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Secu ...
- discuz电脑访问手机版域名怎么跳转到电脑版本
用discuz论坛访问手机版本的域名不会自动跳转到电脑版本,而是会跳转到域名+misc.php?mod=mobile体验很不好.现提供修改方法:打开论坛根目录找到文件./source/class/di ...
- WPF实现系统禁音的方法
方法1: [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern ...
- css3 pointer-events 让对象如透明般直接响应下层对象的鼠标事件
引用:http://www.css88.com/book/css/properties/user-interface/pointer-events.htm 语法: pointer-events:aut ...
- MacOS X编译OpenSceneGraph
本文主要记录在MacOS X上编译OpenSceneGraph,方便日后查阅.所使用的环境如下: MacOS X 10.10 Yosemite XCode 6.3.2 CMake 3.3.0 Open ...
- 栈内存不是只有2M吗?为什么不溢出?
#include <stdio.h> #include <wchar.h> #include <stdlib.h> #define MAX_PATH 1024 FI ...
- <%@ Application Codebehind="Global.asax.cs" Inherits="XXX.MvcApplication" Language="C#" %>
<%@ Application Codebehind="Global.asax.cs" Inherits="XXX.MvcApplication" Lan ...
- 演练:创建和使用动态链接库 (C++)
我们将创建的第一种类型的库是动态链接库 (DLL). 使用 DLL 是一种重用代码的绝佳方式. 您不必在自己创建的每个程序中重新实现同一例程,而只需对这些例程编写一次,然后从需要该功能的应用程序引用它 ...
- [書訊]《.NET 依賴注入》 (2014-12-08 更新)
书 名:.NET 依赖注入 页 数:235 格 式:PDF.EPUB.MOBI难易度:中阶至进阶出版日期:2014 年 12 月 8 日ISBN:9789574320684 简介 本书内容是关于 .N ...
- linux log rotate
今天老大提醒我产线kafka自身的log文件积累了好几个月了,我才发现原来kafka的log4j并删除old log. 第一反应是采用linux自带的logrotate功能,在/etc/logrota ...