Five steps to master the basic use of the OOM framework AutoMapper, oomautomapper

Source: Internet
Author: User

Five steps to master the basic use of the OOM framework AutoMapper, oomautomapper

This article is copyrighted by the blog and the author Wu Shuang himself. for reprinting and crawlers, please enter the original address www.cnblogs.com/tdws.

Preface

OOM, as its name implies, is the process of converting Object-Mapping objects to each other. AutoMapper is also an old saying. Its significance is to help you do not need to manually convert simple and troublesome inter-entity relationships, for example, the conversion of ViewModel and entity, the conversion of SearchModel and Entity, the significance of this article is that most of the online sharing is a few years ago, and many methods have been discarded, in the compiler, it will tell you that the method is outdated, obsolete, and not recommended, such as Mapper. createMap and other methods. Of course, most old drivers go directly to github to read the document, or google to understand it. However, after the Chinese documents are discarded, there is no explanation. 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 that you interact with users. TModel is the entity you deal with databases.

The entity is 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; }    }

The following three viewmodels are available:

 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 object, if the attribute field name exactly matches, you only need to specify the conversion rules between the two entities and specify the source and destination target entities. 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);

Note that in AutoMapper5.x, Initialize is the first choice to Initialize your rules.

After you specify a conversion rule, use the Map method to convert and output your target object. The first parameter represents SourceModel, and the second parameter is DestinationModel.

Attribute conversion for different names of a single object

When you need to map fields of different names, please note that the ForMember method is used. The first parameter requires you to specify the target field for special configuration, for the second parameter, You need to define your operation on the attribute of this field. I chose the MapFrom method provided by it, which means to tell AutoMapper, the City source of the target object is specified as the City2 attribute value of the source object.

            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

During Inter-set conversion, you do not need to configure the matching between the target List and the source List object, but only need to configure the ing 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> (); // here, you only need to configure conversions between entities, rather than the conversion List of object sets <VM_Address> res = Mapper. map <List <TAddress>, List <VM_Address> (addressList );

 

Object contains different types of attribute conversion (ignore attribute conversion)

When an object contains different types of attributes, for example, TModel1 contains a List <TModel>, and ViewModel1 contains a List <ViewModel>. you can ignore this attribute at this time.

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 = "Description", Name = "Wu Shuang", 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 indicates that the operation for configuring ContractInfo is to Ignore. This attribute is ignored during ing BECAUSE List <TContactInfo> () and List <VM_ContactInfo> () are of different types, therefore, ignore or special ing needs to be configured. For special ing examples, see the following

 

Object contains different types of property conversion (specifying the property Mapfrom)

Of course, when you need this attribute, you can use MapFrom instead of ignoring it. In addition, when the types are different, you must specify the ing between the two types. As shown in the following example:

M. CreateMap <TContactInfo, VM_ContactInfo> (); and
m.CreateMap<TAuthor, VM_Author>().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 = "Description", Name = "Wu Shuang", ContactInfo = contacts}; Mapper. initialize (m => {m. createMap <TContactInfo, VM_ContactInfo> (); // pay attention to the necessary m for converting different types of internal entities. createMap <TAuthor, VM_Author> (). forMember (x => x. contactInfo, opt => opt. mapFrom (o => o. contactInfo); // note that MapFrom is necessary}); VM_Author dto = Mapper. map <TAuthor, VM_Author> (author );

 

Conclusion

In Entity conversion, the necessity and practicality of AutoMapper have been shown at a glance.

If my share is helpful to you, click the red button below to continue sharing. You are also welcome to likes for yourself and for me.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.