


Take you to master the usage examples of OOM framework AutoMapper
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);
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.
