Fixed and Dynamic Values in Destination Property using Automapper in ASP.NET Core Web API

Fixed and Dynamic Values in Destination Property in ASP.NET Core Web API

In this article, I will discuss How to Store Fixed and Dynamic Values in Destination Properties using Automapper in ASP.NET Core Web API with Examples. Please read our previous article discussing Automapper Null Substitution with Simple and Complex Types in ASP.NET Core Web API with Examples.

Storing Fixed and Dynamic Values in Destination Property using Automapper in ASP.NET Core Web API

AutoMapper is a popular .NET library used to map one object to another, simplifying the code needed to assign values from one object’s properties to another’s. AutoMapper allows you to map fixed values or dynamically computed values to destination properties during the mapping process, which can be useful for setting constants or applying transformation logic during the mapping process.

Storing fixed and dynamic values in destination properties using AutoMapper in an ASP.NET Core Web API involves configuring mapping profiles to specify how data should be transferred between objects. Let us proceed and understand this with an example using ASP.NET Core Web API. First, create the following Product and ProductDTO.

Product Model:

Create a class file named Product.cs, and then copy and paste the following code.

namespace AutomapperDemo.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }

        //Set with Dynamic Value, i.e., Current Date and Time using Automapper while creating a new Product Object
        public DateTime CreatedOn { get; set; }

        //Set with Static of Fixed Value, i.e., Admin using Automapper while creating a new Product Object
        public string CreatedBy {  get; set; }
    }
}
ProductDTO:

Create a class file named ProductDTO.cs and then copy and paste the following code.

namespace AutomapperDemo.Models
{
    public class ProductDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int ItemQuantity {  get; set; }
    }
}
Business Requirement:

Our business Requirement is to Map the ProductDTO Object with the Product object while creating a new Product using the HTTP Post Method. As you can see in the Product object, we have CreatedOn and CreatedBy properties for which there is no corresponding property in the ProductDTO object. So, here, while doing the mapping, we want to store the Static or Fixed value “System” as the Value for the CreatedBy property and the Current DateTime value as the Value from the CreatedOn Property.

We need to use the MapFrom method to assign fixed and dynamic values to the destination property. So, create a class file named MyMappingProfile.cs and copy and paste the following code. In the below code, we are assigning Fixed and Static values to destination properties.

using AutoMapper;
namespace AutomapperDemo.Models
{
    public class MyMappingProfile : Profile
    {
        public MyMappingProfile()
        {
            // Example mapping from Source, i.e., ProductDTO to Destination model. i.e., Product 
            CreateMap<ProductDTO, Product>()

                //As Property Name Quantity and ItemQuantity are different, specify the same using ForMember methid
                .ForMember(dest => dest.Quantity, opt => opt.MapFrom(src => src.ItemQuantity))

                //Fixed Value Mapping, i.e., Storing System in the CreatedBy Property
                .ForMember(dest => dest.CreatedBy, opt => opt.MapFrom(src => "System"))

                //Dynamic Value Mapping, i.e., Storing Current Date and Time in the CreatedOn Property
                .ForMember(dest => dest.CreatedOn, opt => opt.MapFrom(src => GetCurrentDateTime()));
        }

        //Method to Return Dynamic Value
        public static DateTime GetCurrentDateTime()
        {
            //Write the Logic to Get Dynamic value
            return DateTime.Now;
        }
    }
}

Here,

  • We have created one method called GetCurrentDateTime that is used to return the current system data time.
  • Using the ForMember and MapFrom methods, we are assigning the hard-coded or fixed value System to the CreatedBy destination Property.
  • We are assigning the dynamic value to the destination CreatedOn property within the MapFrom method by calling the GetCurrentDateTime method and whatever dynamic value the GetCurrentDateTime method returns that we are assigning to the CreatedOn property.
  • As the Quantity and ItemQuantity Property names are different, so explicitly mapping the same using the ForMember method.
Register AutoMapper in Program.cs

Register AutoMapper and profiles with the dependency injection container in the Program.cs class file. So, please add the following statement within the Program class. This configuration tells AutoMapper to scan the assembly (or assemblies) for classes that inherit from Profile and automatically register them.

builder.Services.AddAutoMapper(typeof(Program).Assembly);

Using AutoMapper in Controller

When performing the create operation in your service or controller, use AutoMapper to map the DTO to the entity. The Automapper ensures that the CreatedOn and CreatedBy properties are filled with the actual values. So, create an API Empty Controller named Product and then copy and paste the following code:

using AutoMapper;
using AutomapperDemo.Models;
using Microsoft.AspNetCore.Mvc;

namespace AutomapperDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        //Create a variable to holder mapper instance
        private readonly IMapper _mapper;

        //Framework will inject the instance using Constructor
        public ProductController(IMapper mapper)
        {
            //Initialize the variable with the injected mapper instance
            _mapper = mapper;
        }

        private List<Product> listProducts = new List<Product>()
        {
            new Product { Id = 1001, Name="Laptop", Price = 1000, Quantity = 10, CreatedBy = "System", CreatedOn=DateTime.Now},
            new Product { Id = 1002, Name="Desktop", Price = 2000, Quantity = 20, CreatedBy = "System", CreatedOn=DateTime.Now}
        };

        [HttpPost]
        public ActionResult<Product> CreateProduct(ProductDTO productDTO)
        {
            if (productDTO == null || productDTO.Id > 0)
            {
                return BadRequest();
            }

            // AutoMapper will store Fixed and Dynamic Values for CreatedBy and CreatedOn Property
            var product = _mapper.Map<Product>(productDTO);

            //Once Mapping is done, set the Product ID using the Business Logic
            product.Id = 1003;

            //Add the Product into the Database
            listProducts.Add(product);

            //We are returning the newly created product to see the data
            return Ok(product);
        }
    }
}
Testing the API:

Let us test the above endpoint using Postman and see the results.

API: Create a New Product

URL: api/Product

Method: POST

Request Body:

{
  "name": "Mobile",
  "price": 1500,
  "itemQuantity": 10
}
Using Postman:

How to Store Fixed and Dynamic Values in Destination Properties using AutoMapper in ASP.NET Core Web API with Examples

Key Points:
  • Storing Fixed Values: Storing a fixed value into a destination property is straightforward. You can use the ForMember method to specify the destination property and then use the MapFrom method to set a fixed value.
  • Storing Dynamic Values: Dynamic values can be based on the source object, external variables, or complex calculations. You use a similar ForMember method but provide a lambda expression or a method to dynamically compute the value.
When Should We Store Fixed and Dynamic Values in Destination Property in ASP.NET Core Web API?

Deciding when to store fixed and dynamic values in a destination property using AutoMapper depends on the specific requirements of your application and the nature of the data being mapped. Here’s a guideline to help you make an informed decision:

Storing Fixed Values

Fixed values are constants or values that do not change based on the input data. You might want to store a fixed value in a destination property when:

  • Default Values: You want to provide a default value for a property in the destination object that is not present or has no equivalent in the source object. For example, setting a default status for new entities that are being mapped.
  • Static Configuration: You need to set a property to a value that is constant across all instances of a mapping, possibly for configuration purposes or to meet certain business rules.
  • Flag Setting: You want to set flags or indicators that are constant for all mappings of a particular type. This could be useful for differentiating between objects created or mapped through different processes.
Storing Dynamic Values

Dynamic values are those that change based on the input data or during the runtime of the application. You might want to store a dynamic value in a destination property when:

  • Calculated Properties: The value of the property in the destination object is calculated based on other properties of the source object. For example, calculating an Age property based on a DateOfBirth field.
  • Conditional Logic: You need to apply conditional logic to determine the value of a property in the destination object based on one or more properties of the source object. AutoMapper’s Condition and MapFrom can be particularly useful in these scenarios.
  • External Data Sources: The value needs to be obtained from an external source or service at runtime. For instance, fetching and mapping data from a database or an API to fill a property in the destination object.

In the next article, I will discuss HTTP Methods in ASP.NET Core Web API with Examples. In this article, I explain How to Store Fixed and Dynamic Values in Destination Properties using AutoMapper in ASP.NET Core Web API with Examples. I hope you enjoy this article, “Fixed and Dynamic Values in Destination Property using AutoMapper in ASP.NET Core Web API.”

Leave a Reply

Your email address will not be published. Required fields are marked *