2

Using Property Mappings in AutoMapper To Define Mapping Rules

 4 weeks ago
source link: https://code-maze.com/csharp-getting-property-mappings-from-automapper/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Using Property Mappings in AutoMapper To Define Mapping Rules

We value your privacy

We and our store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised advertising and content, advertising and content measurement, audience research and services development. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our 823 partners’ processing as described above. Alternatively you may click to refuse to consent or access more detailed information and change your preferences before consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences or withdraw your consent at any time by returning to this site and clicking the "Privacy" button at the bottom of the webpage.

Represent the Relationship of Properties Using Property Mappings From AutoMapper

Posted by Gang Zhu | Apr 21, 2024 | 0

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

In this article, we’ll take a look at what property mappings are and how to retrieve them from AutoMapper.

AutoMapper is a free .NET library that streamlines object mapping, reducing manual coding to boost development speed and minimize the risk of errors. Additionally, it offers versatile configuration options and supports complex needs like conditional mapping, custom transformations, and error handling.

To download the source code for this article, you can visit our GitHub repository.

Let’s start

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Using AutoMapper to Map Classes

We already have prepared a basic mapping functionality, so let’s check that out. If you haven’t used AutoMapper before, check out this article first Getting Started with AutoMapper in ASP.NET Core.

Creating a Basic Mapping Configuration

First, we have two classes to be mapped, Source and Destination:

public class Source
public string Name { get; set; }
public int Age { get; set; }
public class Destination
public string FullName { get; set; }
public int YearsOld { get; set; }
public class Source
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Destination
{
    public string FullName { get; set; }
    public int YearsOld { get; set; }
}

Then, there is a mapping profile:

public class MyProfile : Profile
public MyProfile()
CreateMap<Source, Destination>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.YearsOld, opt => opt.MapFrom(src => src.Age));
public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<Source, Destination>()
            .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => src.Name))
            .ForMember(dest => dest.YearsOld, opt => opt.MapFrom(src => src.Age));
    }
}

Note that if we don’t explicitly call the ForMember() method to specify the fields to be mapped, AutoMapper will look for properties or fields with the same name in the Source and Destination classes.

Finally, we have a new MapperConfiguration in the Program class:

var config = new MapperConfiguration(cfg =>
cfg.AddProfile(new MyProfile());
var config = new MapperConfiguration(cfg =>
{
    cfg.AddProfile(new MyProfile());
});

Performing Mapping Operations

Now let’s map an instance of the Source class to the Destination class:

var mapper = config.CreateMapper();
var source = new Source { Name = "Jack",Age = 20};
var destination = mapper.Map<Source, Destination>(source);
Console.WriteLine($"Name: {destination.FullName}, Age: {destination.YearsOld}");
var mapper = config.CreateMapper();
var source = new Source { Name = "Jack",Age = 20};
var destination = mapper.Map<Source, Destination>(source);
Console.WriteLine($"Name: {destination.FullName}, Age: {destination.YearsOld}");

First, we build the IMapper object. Then we create an instance of Source as the source object and use the Map() method of the IMapper object to produce a Destination object. Finally, we output the properties of the mapped object to verify that the mapping operation was successful.

Let’s run the application and verify that the console displays the values of FullName and YearsOld in the mapped Destination object:

Name: Jack, Age: 20
Name: Jack, Age: 20

What Are Property Mappings?

Now let’s take a look at property mappings, which represent the relationship of properties between source and target objects.

Is this material useful to you? Consider subscribing and get ASP.NET Core Web API Best Practices eBook for FREE!

In AutoMapper, when we create a mapping configuration between two types, we define a series of mappings between source and target object properties. These property mappings define the rules for converting object properties correctly and can be as straightforward or complex as necessary.

Getting Property Mappings

The ability to retrieve property mappings helps us debug complex mapping configurations, generate test cases based on mapping relationships, and dynamically adjust mapping rules to conditions at runtime.

In AutoMapper, we get the defined property mappings by calling the GetAllTypeMaps() method:

var typeMaps = mapper.ConfigurationProvider.Internal().GetAllTypeMaps();
foreach (var typeMap in typeMaps)
foreach (var memberMap in typeMap.MemberMaps)
Console.WriteLine(
$"{typeMap.SourceType.Name}.{memberMap.SourceMember.Name} "
+ $"is mapped to {typeMap.DestinationType.Name}.{memberMap}");
var typeMaps = mapper.ConfigurationProvider.Internal().GetAllTypeMaps();
foreach (var typeMap in typeMaps)
{
    foreach (var memberMap in typeMap.MemberMaps)
    {
        Console.WriteLine(
            $"{typeMap.SourceType.Name}.{memberMap.SourceMember.Name} "
            + $"is mapped to {typeMap.DestinationType.Name}.{memberMap}");
    }
}

Here, we retrieve a TypeMap collection, where each TypeMap represents a specific mapping relationship between two classes.

The typeMap.MemberMaps collection represents the mapped properties. typeMap.SourceType.Name returns the source class name, while memberMap.SourceMember.Name gets the mapped source property. typeMap.DestinationType.Name returns the destination class name and finally, memberMap gets the mapped destination property. 

Let’s rerun the application to see the mapped relationships:

Name: Jack, Age: 20
Source.Name is mapped to Destination.FullName
Source.Age is mapped to Destination.YearsOld
Name: Jack, Age: 20
Source.Name is mapped to Destination.FullName
Source.Age is mapped to Destination.YearsOld

Here, we only created a single map in the MyProfile class between two classes. Had we created additional mappings between other classes, GetAllTypeMaps() would also have retrieved those relationships. Subsequently, we would have seen those additional relationships displayed in the console.

Conclusion

In this article, we covered the basic usage of AutoMapper, as well as property mappings and why being able to retrieve them is important. Finally, we learned how to get property mappings through a simple example.

Is this material useful to you? Consider subscribing and get ASP.NET Core Web API Best Practices eBook for FREE!

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!

Share:

Subscribe
guest
Label
0 Comments
asp.net core web api best practices booklet

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices.

Leave this field empty if you're human:

© Copyright code-maze.com 2016 - 2024

You WILL Get Stuck On A Coding Interview - 4 Tips to Unstuck | Coding Interview Tips
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTI1JaNypaZypyRcoWU9MTpkMmtjNmMlNSZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTEkODM0JaN0YT0jJat9NDAjJax9MwplJaZcZF9jYXNmRG9gYWyhPWNiZGUgoWF6ZS5wo20zp3VvSWQ9Y29xZS1gYXcyLzNioSZxZWJ1Z0yhZz9loWF0nW9hPSZcp0FjpD0jJaNxn3Y9JaVmZXJJpEFxZHI9NDUhNmphMTp4LwImNSZ1p2VlVUE9TW96nWkfYSUlRwUhMCUlMCUlOFtkMSUmQvUlMEkcoaV4JTIjrDt2XmY0JTI5JTIjQXBjoGVXZWJLnXQyMxY1MmphMmYyMwAyMwuLSFRNTCUlQlUlMGkcn2UyMwBHZWNeolUlOSUlMEuyYWRfZXNmQ2ulo21yJTJGMTAkLwAhNDx1MS42NCUlMFNuZzFlnSUlRwUmNl4mNvZwp3V1nWQ9NwYlNwyzZGM0NGI1YSZwo250ZW50RzyfZUyxPTAzoWVxnWFQoGF5TGymqEyxPTAzoWVxnWFMnXN0SWQ9MCZxqXI9NTYkJzqxpHI9MCZaZHBlQ29hp2VhqD0znXNXZVBup3NHZHBlPTEzY2NjYT0jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE3MTM4MDpmOTt3NmtzqWyxPVNyn2yhZG9TUGkurWVlNwYlNwyzZGRvYWVxNlZjqWJVpzj9nHR0pHMyM0EyMxYyMxZwo2RyLW1urzUhY29gJTJGY3NbYXJjLWqyqHRcozpgpHJipGVlqHxgoWFjpGyhZ3MgZaJioS1uqXRioWFjpGVlJTJGJzZfo2F0U3RuqHVmPXRlqWUzZWyxp3A9nWykJaB4nWQ9YTBuMmyzNmE3OGM1YwZyNzNwMDQ3NDVyNmE3Nwt4ZTx=liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2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