The foundation is the top priority ~ AutoMapper is the ing of existing target objects.

Source: Internet
Author: User

The foundation is the top priority ~ AutoMapper is the ing of existing target objects.

Back to directory

AutoMapper, you will not be unfamiliar. Uncle also mentioned in his previous articles that he once wrote extension methods to facilitate program developers to use them. Recently, in an API project, when a POST request assigned a value from a DTO object to an object, uncle had to supplement the original extension method.

This is the case. There is a DTO object RequestUserInfo and a database entity object UserInfo. During POST, the value of the RequestUserInfo object needs to be assigned to the UserInfo object, we know that the DTO object is extracted from UserInfo according to the interface requirements, and its attributes are smaller than UserInfo. In this case, no problem occurs during the GET request (ing from userinfo to RequestUserInfo ), assign the corresponding property value to the DTO object. because the number of attributes of the DTO object is small during POST, some attributes of UserInfo are not assigned a value and Null occurs.

/// <Summary> /// DTO user-Request Parameter // each attribute of the input parameter can be empty. If it is null, verification is not performed, and the query condition is not constructed during the query. /// </summary> public class RequestUserInfo: RequestBase {public int? Id {get; set;} [MaxLength (10, ErrorMessage = "UserName can be up to 10 characters")] public string UserName {get; set ;} [EmailAddress (ErrorMessage = "the Email address is invalid")] public string Email {get; set;} [MaxLength (20, ErrorMessage = "the user name cannot exceed 20 characters")] public string RealName {get; set ;}}
Public class UserInfo: Entity {[DisplayName ("username"), Required] // StringLength (50, MinimumLength = 4, ErrorMessage = "username can only be ~ Consisting of 50 characters ") public string UserName {get; set;} [DisplayName (" Real Name "), Required] // StringLength (30, MinimumLength = 6, errorMessage = "the real name can only be 6 ~ Consisting of 30 characters ") public string RealName {get; set;} [DisplayName (" password "), Required] // StringLength (20, MinimumLength = 6, errorMessage = "the password ranges from 6 ~ Consisting of 20 characters ") public string Password {get; set;} [DisplayName (" Email "), Required, EmailAddress] public string Email {get; set ;}}

The above are the content of the two objects. In the concept of AutoMapper, In the GET request, UserInfo is equivalent to the TSource object, and RequestUserInfo is equivalent to the TResult target object,In the POST request, this is the opposite. Therefore, the extended method we defined earlier has a problem. It will change some attributes in UserInfo to null.This is normal, because when performing AutoMapper, if you do not pass it the target object, it will automatically build a new object.

The method before expansion. It supports AutoMapper to assign values to existing target objects.

 

/// <Summary> /// perform automapper for an existing object // </summary> /// <typeparam name = "TSource"> </typeparam> // /<typeparam name = "TResult"> </typeparam> // <param name = "self"> </param> // <param name = "result"> </param> // <returns> </returns> public static TResult MapTo <TResult> (this object self, TResult result) {if (self = null) throw new ArgumentNullException (); Mapper. createMap (self. getType (). underlyingSystemType, typeof (TResult); return (TResult) Mapper. map (self, result, self. getType (), typeof (TResult ));}

 

In this way, the result of an existing object will be passed in as a parameter when the program is called. The following code

   public void Update(RequestUserInfo request)        {            var entity = userRepository.GetModel().FirstOrDefault(i => i.Id == request.Id);            request.MapTo<UserInfo>(entity);            userRepository.Update(entity);        }

At this time, entity is the complete data obtained from the database. Then, it automatically maps and assigns values to its DTO attribute. Finally, it updates the assigned object!

The above is the general practice in the ORM tools such as EF and LINQ, that is, taking out the object first, assigning new values for the specified attribute, and finally submitting it to the database!

Thank you for reading this article!

Back to directory

 

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.