search
HomeBackend DevelopmentC#.Net TutorialIntroducing the use of AutoMapper in OOM

This article mainly introduces the relevant knowledge of the OOM framework AutoMapper. 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 entities convert each other, AutoMapper It is also a cliché. Its meaning is to help you convert simple and troublesome relationships between entities without manual work, 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 is It was a few years ago, and many methods have been abandoned. When you get it, the compiler will tell you that the method is outdated, abandoned, and not recommended for use, such as Mapper.CreateMap and other methods. Of course, most experienced drivers go directly to github to read the documentation. Or you can just google it to find out, but the Chinese information doesn’t have any explanation about the method after it was 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, in AttributesField name In the case of an exact match, you only need to specify the conversion rules between the two entities, specifying the source entity and destination 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 choose The MapFrom method it provides 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 matching between the target List and the source Listobject, but only You need to configure the mapping matching relationship of your generic objects.

  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);

Entity contains different types of attribute conversion (ignore attributes)

When the entity contains different types of attributes, for example, TModel1 contains a List, and Your ViewModel1 contains a List. At this time, you can choose to ignore this attribute

 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 don't need to ignore it, but use MapFrom to specify it specifically. And when the types are different, you need to specify the mapping relationship between your two types. As in the examples below

m.CreateMap(); and
m.CreateMap().ForMember(x => x.ContactInfo, opt => ; opt.MapFrom(o => o.ContactInfo));

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);

【Related recommendations】

1. ASP Free Video Tutorial

2. ASP tutorial

3. Li Yanhui ASP basic video tutorial

The above is the detailed content of Introducing the use of AutoMapper in OOM. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the alternatives to NULL in C languageWhat are the alternatives to NULL in C languageMar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

How to add next-level C compilerHow to add next-level C compilerMar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

Which C language compiler is better?Which C language compiler is better?Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language?Is NULL still important in modern programming in C language?Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers?What are the web versions of C language compilers?Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

C language online programming website C language compiler official website summaryC language online programming website C language compiler official website summaryMar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

Method of copying code by C language compilerMethod of copying code by C language compilerMar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

How to solve the problem of not popping up the output window by the C language compilerHow to solve the problem of not popping up the output window by the C language compilerMar 03, 2025 pm 05:40 PM

This article troubleshoots missing output windows in C program compilation. It examines causes like failing to run the executable, program errors, incorrect compiler settings, background processes, and rapid program termination. Solutions involve ch

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!