When engaged on purposes, you’ll usually must convert one sort to a different. Object mapping is the method of mapping a supply object to a vacation spot object, the place the forms of the supply and vacation spot objects would possibly differ.
For instance, you would possibly must create an occasion of 1 class from an occasion of one other class, then copy the info from the supply object to the vacation spot object. Though there are numerous object mappers obtainable to make use of, it’s possible you’ll must implement your personal customized mappers in sure conditions. On this article, we’ll see how we will implement a easy however quick object mapper in C#.
Create a console utility undertaking in Visible Studio
First off, let’s create a .NET Core console utility undertaking in Visible Studio. Assuming Visible Studio 2022 is put in in your system, observe the steps outlined under to create a brand new .NET Core console utility undertaking.
- Launch the Visible Studio IDE.
- Click on on “Create new undertaking.”
- Within the “Create new undertaking” window, choose “Console App (.NET Core)” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Configure your new undertaking” window, specify the identify and placement for the brand new undertaking.
- Click on Subsequent.
- Within the “Further data” window, select “.NET 8.0 (Lengthy Time period Help)” because the framework model you want to use.
- Click on Create.
We’ll use this .NET 8 console utility undertaking to implement a customized object mapper within the subsequent sections of this text.
AutoMapper advantages and limitations
The favored object mapping library AutoMapper is a wonderful alternative while you wish to map objects of incompatible sorts having comparable property names and construction. AutoMapper works properly with Entity Framework, and writing unit exams for sorts that use AutoMapper is simple. One you might have arrange the mapping between the categories, all you need to do is write just a few strains of code to check the properties of the vacation spot occasion.
AutoMapper has a number of advantages that make it some of the extensively used mapping libraries round. However, there are eventualities by which we should always design our personal customized object mappers in lieu of utilizing any third-party object mapper. For instance, whereas you should use AutoMapper when the vacation spot sort contains a flattened subset of properties of the supply sort, AutoMapper isn’t effectively fitted to advanced layered architectures, or architectures that require advanced mapping logic between objects of incompatible sorts.
Furthermore, even for those who use the newest variations of AutoMapper in your utility, there are efficiency drawbacks you need to be conscious of. If you happen to use a customized mapper, you’ll have extra fine-grained management over the design, which suggests you’ll be able to write code to optimize your customized object mapper.
What’s a customized object mapper? Why do we’d like it?
A customized object mapper is a element used to map or rework a supply object of 1 sort to a vacation spot object of one other sort. You need to use a customized object mapper to deal with advanced mapping logic and tailor the mapping logic to cater to the wants of your utility. Customized object mappers are helpful in eventualities the place you should map objects of incompatible sorts, i.e., when the categories haven’t any inherent mapping relationship.
A customized object mapper makes code simpler to learn and keep, and permits you to reuse mappings between tasks. It reduces the processing time wasted on handbook mappings, offering added flexibility to deal with difficult eventualities with nested object collections. If you happen to use a customized object mapper, it is possible for you to to map information between advanced and numerous information buildings.
You may keep away from writing pointless mapping logic by encapsulating it inside a customized mapper after which reusing it all through the applying. When creating the fashions and entities that make up your utility, it is strongly recommended to make use of light-weight information buildings somewhat than hefty ones with a purpose to obtain optimum pace.
Typical use circumstances for a customized object mapper
Listed here are just a few causes you would possibly want to make use of a customized object mapper:
- Help for mapping incompatible information buildings: An object mapper bridges the hole between two lessons or information buildings that symbolize comparable data however have totally different property names, sorts, or buildings. You may reap the benefits of an object mapper to repeat information from the supply object to the vacation spot object even when the objects possess comparable or dissimilar names or information buildings.
- Help for integration with exterior elements: When working with exterior APIs or databases, you would possibly must deal with information fashions that aren’t aligned completely together with your inner information fashions. You need to use a customized object mapper to deal with the mapping logic between totally different programs and information buildings, primarily for sorts which have differing property names.
- Help for versioning: Over time, your software program will evolve in accordance with adjustments in enterprise necessities. These necessities might embrace eradicating legacy sorts and fashions and introducing new sorts and fashions. You may simply deal with the transformation to the brand new model of your fashions for those who’re utilizing a customized mapper as a substitute of a third-party mapper comparable to AutoMappеr.
- Efficiency optimization: A customized mapper permits you to write efficiency optimization code in your sorts and to manage which properties are mapped, thereby lowering pointless overhead and bettering efficiency. Moreover, you’ll be able to write customized code to compress or decompress information, thereby lowering the community bandwidth and bettering efficiency.
- Area-specific processing: A customized mapper additionally permits you to write code for domain-specific guidelines and transformations in your sorts. For instance, you would possibly must carry out particular enterprise operations, execute sure enterprise guidelines, or carry out information conversions which are particular to your utility area. In such circumstances, you’ll be able to reap the benefits of a customized object mapper to include code for domain-specific guidelines, information conversions, and transformations.
A customized object mapper instance in C#
Allow us to now dig right into a little bit of code. Think about the next two lessons.
public class AuthorModel { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Deal with { get; set; } } public class AuthorDTO { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Deal with { get; set; } }
The next code itemizing implements a customized object mapper that maps a supply object to a vacation spot object.
public class CustomObjectMapper { public TDestination Map<TSource, TDestination>(TSource sourceObject) { var destinationObject = Activator.CreateInstance<TDestination>(); if (sourceObject != null) { foreach (var sourceProperty in typeof(TSource).GetProperties()) { var destinationProperty = typeof(TDestination).GetProperty (sourceProperty.Identify); if (destinationProperty != null) { destinationProperty.SetValue (destinationObject, sourceProperty.GetValue(sourceObject)); } } } return destinationObject; } }
You need to use the next code snippet to make use of the customized mapper. Be aware how the generic Map methodology has been used to map an occasion of sort AuthorModel to an occasion of AuthorDTO.
var supply = new AuthorModel(); supply.Id = 1; supply.FirstName = "Joydip"; supply.LastName = "Kanjilal"; supply.Deal with = "Hyderabad, India"; CustomObjectMapper mapper = new CustomObjectMapper(); var vacation spot = mapper.Map<AuthorModel, AuthorDTO>(supply); Console.WriteLine("Id = {0}, First Identify = {1} Final Identify = {2} Deal with = {3}", vacation spot.Id, vacation spot.FirstName, vacation spot.LastName, vacation spot.Deal with); Console.ReadLine();
Use a customized object mapper in motion strategies in C#
On this part, we’ll look at how you can use our customized mapper in motion strategies. First create an interface known as IAuthorRepository and enter the next code.
public interface IAuthorRepository { public AuthorDTO GetAuthor(int id); }
The AuthorRepository class will implement this interface. So, create a brand new class named AuthorRepository and write the next code in there.
public class AuthorRepository : IAuthorRepository { personal readonly CustomObjectMapper _customObjectMapper; public AuthorRepository(CustomObjectMapper customObjectMapper) { _customObjectMapper = customObjectMapper; } public AuthorDTO GetAuthor(int id) { var sourceObject = GetAuthorInstance(id); var destinationObject = _customObjectMapper.Map<AuthorModel, AuthorDTO>(sourceObject); return destinationObject; } }
Now, create one other class named AuthorController and change the auto-generated code with the next code itemizing.
public class AuthorController : ControllerBase { personal readonly IAuthorRepository _authorRepository; public AuthorController(IAuthorRepository authorRepository) { _authorRepository = authorRepository; } public IActionResult GetAuthor(int id) { var creator = _authorRepository.GetAuthor(id); //Write your code right here primarily based on particular enterprise guidelines return Okay(creator); } }
Be aware that in each of those lessons dependency injection has been used to inject dependencies within the constructors. The AuthorRepository class encapsulates all calls to the customized mapper. That is why we now have not written any code to entry or use the customized mapper within the AuthorController class.
The AuthorController class retrieves information from the database utilizing an occasion of the AuthorRepository, i.e., it doesn’t must work together with the database straight. In different phrases, your controller’s motion strategies shouldn’t comprise code to carry out CRUD operations towards the database straight.
Object mapping isn’t at all times straightforward
Utilizing a customized object mapper permits you to create cleaner, maintainable code bases and streamline information entry and information switch. By profiting from the flexibleness and effectivity of customized object mappers, you’ll be able to construct options that comprise mapping logic tailor-made to your particular necessities.
That mentioned, you’ll be able to keep away from utilizing a customized object mapper if the mapping is trivial, as a result of the mapping will likely be simpler to do with out it. The underside line is you might have many design patterns and approaches to select from. Use AutoMapper when you’ll be able to, and reap the benefits of customized mappers when you should.
Copyright © 2024 IDG Communications, Inc.