AutoMapper (on), AutoMapper (

Source: Internet
Author: User

AutoMapper (on), AutoMapper (
Total returned directory

Operations before and after ing

Occasionally, you may need to execute custom logic before or after ing. This may be rare because it is more obvious to handle these tasks outside of AutoMapper. You can create a global operation before and after ing:

Mapper.CreateMap<Source, Dest>()    .BeforeMap((src, dest) => src.Value = src.Value + 10)    .AfterMap((src, dest) => dest.Name = "John");

You can also create a callback function before and after ing during the ing process:

int i = 10;Mapper.Map<Source, Dest>(src, opt => {    opt.BeforeMap((src, dest) => src.Value = src.Value + i);    opt.AfterMap((src, dest) => dest.Name = HttpContext.Current.Identity.Name);});

The latter configuration is useful when you need to inject context information into the actions before and after ing.

Condition ing

Before property ing, AutoMapper allows you to add conditions that must be met to the property.

This is used in the following situations. For example, there are two classes: Aliens (alien) and Person (Person). They both have an Age attribute. We all know that our human ages are not negative, so here we use the unsigned int (unsigned integer) type. However, at present, the level of human science and technology is limited, and it is impossible to determine whether there are aliens, so let's assume that the age of aliens can be negative (if you refute me, you have no reason, so now), define it as int type, if we want to map aliens to humans, it is actually the ing between uint and int:

Namespace FrontAutoMapper {class Program {static void Main (string [] args) {// creates a ing. The Age ing condition is that the Age attribute of the source type is within the range (0,149). Mapper. createMap <Aliens, Person> (). forMember (dest => dest. age, opt => opt. condition (src => src. age> 0 & src. age <149); var p1 = Mapper. map <Person> (new Aliens () {Age =-1}); // The var ing condition var p2 = Mapper is not met. map <Person> (new Aliens () {Age = 0}); // The var ing condition var p3 = Mapper is not met. map <Person> (new Aliens () {Age = 1}); // conforms to the ing condition var p4 = Mapper. map <Person> (new Aliens () {Age = 148}); // conforms to the ing condition var p5 = Mapper. map <Person> (new Aliens () {Age = 149}); // The Console does not meet the ing conditions. writeLine (p1.Age); // If the ing is unsuccessful, the Person is returned. the default value of Age is 22. writeLine (p2.Age); // If the ing is unsuccessful, the Person is returned. the default value of Age is 22. writeLine (p3.Age); // The ing is successful, and the new value 1 Console is returned. writeLine (p4.Age); // The ing is successful. The new value 148 Console is returned. writeLine (p5.Age); // If the ing is unsuccessful, the new value 22 Console is returned. read () ;}} public class Person {public Person () {Age = 22 ;}public uint Age {set; get ;} // The default value of the Age attribute of Person is 22} public class Aliens {public Aliens () {Age =-23;} public int Age {get; set ;} // The default Age attribute of Aliens is-23 }}

In this example, the Age is mapped to an alien within the range (0,149). The result is as follows, which is consistent with the prediction result.

// Initialize the configuration file Mapper. initialize (cfg => {cfg. createMap <Aliens, Person> (); cfg. addProfile <AliensPersonProfile> (); // Add a configuration file });

The ing configuration is static and should not be changed later.

Profile instance

Used to organize AutoMapper configurations

Namespace ConditionalMapping {public class AliensPersonProfile: Profile {protected override void Configure () {// put some ing configuration operations such as CreateMap }}}

Define a class that inherits the Profile class, and then rewrite the Configure method to add some ing configurations in the method.

Initialize the custom configuration file as follows:

// Initialize the configuration file Mapper. Initialize (cfg =>{ cfg. AddProfile <AliensPersonProfile> (); // Add a configuration file });
Naming Convention

You can set naming conventions for sources and targets.

// Initialize the configuration file Mapper. Initialize (cfg => {cfg. SourceMemberNamingConvention = new condition (); cfg. DestinationMemberNamingConvention = new PascalCaseNamingConvention ();});

You can also set it in the Configure method in the configuration file:

protected override void Configure(){    SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();    DestinationMemberNamingConvention = new PascalCaseNamingConvention();}

Test knife:

Add the following code to the Aliens class:

public string MyName { set; get; }

Add the following code to the Person class:

public string my_name { get; set; }

The result is as follows:

Note that the replacement character must be configured before the CreateMap method, otherwise it will not work. This also complies with the logic. Only by adding replacement conditions can we map them by conditions.

cfg.ReplaceMemberName("Ä", "A");cfg.ReplaceMemberName("í", "i");cfg.ReplaceMemberName("Tool", "Car");cfg.AddProfile<AliensPersonProfile>();

Test knife:

Add the following code to the Aliens class:

public int Ävíator { get; set; }public string ToolName { get; set; }

Add the following code to the Person class:

public int Aviator { get; set; }public string CarName { get; set; }

The result is as follows:

Public string PGender {get; set ;}

Add the following code to the Person class:

public string Gender { get; set; }

It can be seen that the source type has a PGender field prefixed with "P". To map it to Person, you must identify the prefix "P ", therefore, add code in Mapper configuration (note: the code is not valid until it is added to the CreateMap method ):

cfg.RecognizePrefixes("P");

The result is as follows:

Cfg. ClearPrefixes ();Global attribute/field filtering

By default, AutoMapper maps every common attribute/field. You can use the attribute/field filter to filter out attributes/fields that do not need to be mapped:

// Do not map any field cfg. ShouldMapField = fi => false; // only geting getter is the private attribute cfg. ShouldMapProperty = pi => pi. GetMethod! = Null & pi. GetMethod. IsPrivate; cfg. AddProfile <AliensPersonProfile> ();

Test knife:

Add the following code to the Aliens and Person classes respectively:

private string code;public string Code{    private get { return code; }    set { code = value; }}

Add code to the Main method:

var p10 = Mapper.Map<Person>(new Aliens() { Age = 44,Code = "111"});Console.WriteLine(string.Format("Person.Age={0},Person.code={1}",p10.Age,p10.code));//22,111

The results are the same as predictions:

Mapper. initialize (cfg =>{ // ing the property cfg for getter with public or internal. shouldMapProperty = p => p. getMethod. isPublic | p. getMethod. isAssembly; cfg. createMap <Source, Destination> ();});

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.