


This article mainly introduces the relevant knowledge of OOM frameworkAutoMapper. The five examples in this article can help you solve common basic problems. It has a certain reference value. Let’s take a look at it with the editor.
Written in front
OOM As the name suggests, Object-Object-Mapping Mutual conversion between entities, AutoMapper is also a cliché. Its significance is to help you convert simple and troublesome relationships between entities without manually converting, such as the conversion between ViewModel and entity, and the conversion between SearchModel and Entity. The significance of my sharing is that, Most of the sharing on the Internet was a few years ago, and many methods have been abandoned. The compiler will tell you that the method is outdated, abandoned, and not recommended, such as Mapper.CreateMap and other methods. Of course, most of the experienced drivers I just went to github to read the documentation, or I just googled it and found out, but the Chinese information didn’t explain anything about the method being abandoned. The five examples in this article can help you solve common basic problems.
Preparation
First we prepare some ViewModel and TModel. ViewModel is the entity you interact with the user. TModel is the entity you use to deal with the database.
The entities are displayed as follows:
TModel has the following three simple entities. They have independent entities and one-to-many entities.
public class TAddress { public string Country { get; set; } public string City { get; set; } public string Street { get; set; } public string PostCode { get; set; } public string CreateTime { get; set; } public int CreateUserId { get; set; } }
public class TAuthor { public string Name { get; set; } public string Description { get; set; } public List<TContactInfo> ContactInfo { get; set; } } public class TContactInfo { public int Id { get; set; } public string Email { get; set; } public string Blog { get; set; } public string Twitter { get; set; } }
ViewModel is as follows:
public class VM_Address { public string Country { get; set; } public string City { get; set; } public string City2 { get; set; } } public class VM_Author { public string Name { get; set; } public string Description { get; set; } public List<VM_ContactInfo> ContactInfo { get; set; } } public class VM_ContactInfo { public int Id { get; set; } public string Email { get; set; } public string Blog { get; set; } public string Twitter { get; set; } }
Single entity conversion
When converting a single entity, when the attribute field names completely match, you only need to specify the conversion rules between the two entities and specify the source entity and destination target entity. Then you should refer to the following example:
VM_Address dto = new VM_Address { Country = "China", City = "Beijing" }; Mapper.Initialize(m => m.CreateMap<VM_Address, TAddress>()); TAddress address = Mapper.Map<VM_Address, TAddress>(dto);
Please note that in AutoMapper5.x, Initialize is preferred to initialize your rules.
After you specify the conversion rules, please use the Map method to convert and output your target entities. The first parameter represents SourceModel, and the second parameter is DestinationModel.
Conversion of attributes with different names for a single entity
When you need to convert fields with different names When mapping, please pay attention to using the ForMember method. The first parameter requires you to specify the target field that requires special configuration. The second parameter requires you to specify the operation of the field attributes. I chose the MapFrom method it provides. The meaning is to tell AutoMapper that I need to specify the City source of the target entity as the City2 attribute value of the source entity.
VM_Address dto = new VM_Address { Country = "China", City2 = "Beijing" }; Mapper.Initialize(m => m.CreateMap<VM_Address, TAddress>().ForMember(x => x.City, opt => opt.MapFrom(o => o.City2))); TAddress address = Mapper.Map<VM_Address, TAddress>(dto);
Set conversion
When converting between collections, you do not need to configure the target List and source List objects , you only need to configure the mapping matching relationship of your generic object.
TAddress address = new TAddress { Country = "China", City = "Beijing" }; TAddress address2 = new TAddress() { Country = "USA", City = "New York" }; List<TAddress> addressList = new List<TAddress>() { address2, address }; Mapper.Initialize(m => m.CreateMap<TAddress, VM_Address>());//这里仅需配置实体间的转换,而不是实体集合的转换 List<VM_Address> res = Mapper.Map<List<TAddress>, List<VM_Address>>(addressList);
Entities contain different types of attribute conversion (ignore attributes)
When entities contain different types of attributes, such as in TModel1 Contains a List
##
var contacts = new List<TContactInfo>() { new TContactInfo() { Blog = "myblog", Email = "ws@qq.com" }, new TContactInfo() { Blog = "myblog", Email = "ll@qq.com" } }; TAuthor author = new TAuthor() { Description = "描述", Name = "吴双", ContactInfo = contacts }; Mapper.Initialize(m => { m.CreateMap<TAuthor, VM_Author>().ForMember(x => x.ContactInfo, opt => opt.Ignore()); }); VM_Author dto = Mapper.Map<TAuthor, VM_Author>(author); //这里的Ignore代表配置ContractInfo该属性的操作 为 忽略Ignore,映射时将忽略该属性 由于List<TContactInfo>()和List<VM_ContactInfo>() 是不同类型,所以需要配置忽略或者是特殊映射,特殊映射例子看下方
The entity contains Different types of attribute conversion (specified attribute Mapfrom)
Of course, when you need this attribute, you can not ignore it, but use MapFrom to make special designations, and when the types are different, You need to specify the mapping between your two types. As in the examples below m.CreateMapm.CreateMap
var contacts = new List<TContactInfo>() { new TContactInfo() { Blog = "myblog", Email = "ws@qq.com" }, new TContactInfo() { Blog = "myblog", Email = "ll@qq.com" } }; TAuthor author = new TAuthor() { Description = "描述", Name = "吴双", ContactInfo = contacts }; Mapper.Initialize(m => { m.CreateMap<TContactInfo, VM_ContactInfo>();//注意 内部不同类型实体转换时必要的 m.CreateMap<TAuthor, VM_Author>().ForMember(x => x.ContactInfo, opt => opt.MapFrom(o => o.ContactInfo));//注意 制定MapFrom是必要的 }); VM_Author dto = Mapper.Map<TAuthor, VM_Author>(author);In entity conversion, the necessity and practicality of AutoMapper have been clearly seen by you.
The above is the detailed content of Take you to master the usage examples of OOM framework AutoMapper. For more information, please follow other related articles on the PHP Chinese website!

Python中的支持向量机(SupportVectorMachine,SVM)是一个强大的有监督学习算法,可以用来解决分类和回归问题。SVM在处理高维度数据和非线性问题的时候表现出色,被广泛地应用于数据挖掘、图像分类、文本分类、生物信息学等领域。在本文中,我们将介绍在Python中使用SVM进行分类的实例。我们将使用scikit-learn库中的SVM模

随着新一代前端框架的不断涌现,VUE3作为一个快速、灵活、易上手的前端框架备受热爱。接下来,我们就来一起学习VUE3的基础知识,制作一个简单的视频播放器。一、安装VUE3首先,我们需要在本地安装VUE3。打开命令行工具,执行以下命令:npminstallvue@next接着,新建一个HTML文件,引入VUE3:<!doctypehtml>

Golang是一门功能强大且高效的编程语言,可以用于开发各种应用程序和服务。在Golang中,指针是一种非常重要的概念,它可以帮助我们更灵活和高效地操作数据。指针转换是指在不同类型之间进行指针操作的过程,本文将通过具体的实例来学习Golang中指针转换的最佳实践。1.基本概念在Golang中,每个变量都有一个地址,地址就是变量在内存中的位置。

随着互联网的普及,验证码已经成为了登录、注册、找回密码等操作的必要流程。在Gin框架中,实现验证码功能也变得异常简单。本文将介绍如何在Gin框架中使用第三方库实现验证码功能,并提供示例代码供读者参考。一、安装依赖库在使用验证码之前,我们需要安装一个第三方库goCaptcha。安装goCaptcha可以使用goget命令:$goget-ugithub

VAE是一种生成模型,全称是VariationalAutoencoder,中文译作变分自编码器。它是一种无监督的学习算法,可以用来生成新的数据,比如图像、音频、文本等。与普通的自编码器相比,VAE更加灵活和强大,能够生成更加复杂和真实的数据。Python是目前使用最广泛的编程语言之一,也是深度学习的主要工具之一。在Python中,有许多优秀的机器学习和深度

随着互联网的迅速发展,数据已成为了当今信息时代最为重要的资源之一。而网络爬虫作为一种自动化获取和处理网络数据的技术,正越来越受到人们的关注和应用。本文将介绍如何使用PHP开发一个简单的网络爬虫,并实现自动化获取网络数据的功能。一、网络爬虫概述网络爬虫是一种自动化获取和处理网络资源的技术,其主要工作过程是模拟浏览器行为,自动访问指定的URL地址并提取所

生成对抗网络(GAN,GenerativeAdversarialNetworks)是一种深度学习算法,它通过两个神经网络互相竞争的方式来生成新的数据。GAN被广泛用于图像、音频、文字等领域的生成任务。在本文中,我们将使用Python编写一个GAN算法实例,用于生成手写数字图像。数据集准备我们将使用MNIST数据集作为我们的训练数据集。MNIST数据集包含

快速上手Django框架:详细教程和实例引言:Django是一款高效灵活的PythonWeb开发框架,由MTV(Model-Template-View)架构驱动。它拥有简单明了的语法和强大的功能,能够帮助开发者快速构建可靠且易于维护的Web应用程序。本文将详细介绍Django的使用方法,并提供具体实例和代码示例,帮助读者快速上手Django框架。一、安装D


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
