Home >Backend Development >C#.Net Tutorial >Take you to master the usage examples of OOM framework AutoMapper

Take you to master the usage examples of OOM framework AutoMapper

零下一度
零下一度Original
2017-07-03 17:19:101691browse

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 Listbc26e2d35896972142bded266172216c, and your ViewModel1 contains a Listc3232db81f7d071f9370eef3d6b791a7. 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 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.CreateMap775d38cc2051b2bc0f39739d39ab1b82(); and

m.CreateMap453162b02c806123692898c984a1fdf8().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);

Write at the end

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!

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