The Mapper pattern in C# is a design pattern used to facilitate the transformation of data between different object types. Its primary goal is to enable seamless conversion without tightly coupling the classes involved. This pattern is particularly useful when dealing with distinct object types that share similar properties but serve different purposes or contexts.
Consider a scenario where you have two classes, Product and ProductDto (Data Transfer Object), each with similar attributes but utilized in different parts of your application:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
Here’s an example of how you could implement a mapper to convert between these two types:
public class ProductMapper
{
public ProductDto MapToDto(Product product)
{
return new ProductDto
{
Id = product.Id,
Name = product.Name,
Price = product.Price
};
}
public Product MapToEntity(ProductDto dto)
{
return new Product
{
Id = dto.Id,
Name = dto.Name,
Price = dto.Price
};
}
}
In this demonstration, the ProductMapper class contains methods for converting a Product object to a ProductDto (MapToDto) and vice versa (MapToEntity).
Here’s an example of how you might use this mapper in your code:
// Creating a Product instance
Product product = new Product
{
Id = 1,
Name = "Example Product",
Price = 29.99
};
// Using the mapper to convert Product to ProductDto
ProductMapper mapper = new ProductMapper();
ProductDto productDto = mapper.MapToDto(product);
// Using the mapper to convert ProductDto to Product
Product convertedProduct = mapper.MapToEntity(productDto);
By employing the Mapper pattern, you separate the conversion logic from the classes themselves. This separation of concerns enhances code maintainability and scalability, allowing for easier modifications and expansions as your application evolves.