How To Ignore Null Values In AutoMapper

In this article, you will learn how to Ignore Null values in AutoMapper in ASP.NET CORE.

In my previous article, I’ve shown how to integrate Automapper feature to our application. In this article, we will learn how to remove null properties from the response body.
 

Requirements

  • Visual Studio 2017 or 2019
  • AutoMapper Nuget Package
  • AutoMapper Dependency Injection Package
I’ve used VS2019 for this example. Let's start!
 
Open Visual Studio, go to File Menu -> New ->Project.
It will display a new project template from where you’ve to choose ASP.NET Core Web Application and click "Next".
 
How To Ignore Null Values In AutoMapper
 
As soon as you click the "Next" button, it will ask to configure the template like below.
 
How To Ignore Null Values In AutoMapper
 
Give a Project Name  -- whatever you feel is meaningful. Here, I’ve given AutoMapperExample.
Click the "Create" button.
After that, it will show the below screen where we’ve to select API template and click the "Create" button.
 
How To Ignore Null Values In AutoMapper
 
The project structure will appear in the Solution Explorer like below.
 
How To Ignore Null Values In AutoMapper
 
First, install Automapper related NuGet packages. For that, right-click on the project and choose the "Manage NuGet Packages" option. 
It’ll open package manager dialog where you’ve to give specific NuGet package name to install. For this demo, we require two AutoMapper NuGet packages -
 

Automapper

 
How To Ignore Null Values In AutoMapper
 
Search for it an click the "Install" button at the right side of the dialogue box.
 

AutoMapper.Extensions.Microsoft.DependencyInjection

 
The second package is AutoMapper.Extensions.Microsoft.DependencyInjection
 
How To Ignore Null Values In AutoMapper
 
Click "Install" and ensure all the required packages are installed, by just checking inside Dependencies under Solution Explorer like below.
 
How To Ignore Null Values In AutoMapper
 
Next, go to the Controllers folder and create Employeecontroller. For this, right-click on the Controllers folder and choose Add->Controller it will show a dialogue as below.
 
How To Ignore Null Values In AutoMapper
 

Choose API Controller

 
It will ask you to enter controller name; here I have given Employee as my controller name.
 
How To Ignore Null Values In AutoMapper
 
Inside the controller, paste the below code snippet.
  1. using System.Collections.Generic;  
  2. using AutoMapper;  
  3. using AutoMapperExample.Data;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. namespace AutoMapperExample.Controllers {  
  6.     [Route("api/[controller]")]  
  7.     [ApiController]  
  8.     public class EmployeeController: ControllerBase {  
  9.         private readonly IMapper _mapper;  
  10.         public EmployeeController(IMapper mapper) {  
  11.             _mapper = mapper;  
  12.         }  
  13.         public IEnumerable < EmployeeDto > PostEmployee(IEnumerable < EmployeeDto > employeeDtos) {  
  14.             Employee employee = new Employee();  
  15.             // mapping EmployeeDto to Employee  
  16.             var employees = _mapper.Map < IEnumerable < EmployeeDto > ,  
  17.                 IEnumerable < Employee >> (employeeDtos);  
  18.             var empList = employee.GetEmployees(employees);  
  19.             var list = _mapper.Map < IEnumerable < Employee > ,  
  20.                 IEnumerable < EmployeeDto >> (empList);  
  21.             return list;  
  22.         }  
  23.     }  
  24. }  
Inside controller, I’ve added the EmployeeDto.cs file with the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. namespace AutoMapperExample.Controllers {  
  6.     public class EmployeeDto {  
  7.         public int Id {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string Name {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Gender {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string Mobile {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string Address {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string Designation {  
  28.             get;  
  29.             set;  
  30.         }  
  31.     }  
  32. }  
Now, create a Data folder under Solution Explorer and keep the Employee.cs file in it.
  1. using AutoMapperExample.Controllers;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. namespace AutoMapperExample.Data {  
  7.     public class Employee {  
  8.         public int Id {  
  9.             get;  
  10.             set;  
  11.         }  
  12.         public string Name {  
  13.             get;  
  14.             set;  
  15.         }  
  16.         public string Gender {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public string Mobile {  
  21.             get;  
  22.             set;  
  23.         }  
  24.         public string Address {  
  25.             get;  
  26.             set;  
  27.         }  
  28.         public string Designation {  
  29.             get;  
  30.             set;  
  31.         }  
  32.         public IEnumerable < Employee > GetEmployees(IEnumerable < Employee > employees) {  
  33.             return employees;  
  34.         }  
  35.     }  
  36. }  
The above two files will appear in Solution Explorer like below.
 
How To Ignore Null Values In AutoMapper
 
If you observe EmployeeController, I’ve injected IMapper on constructor level and along with that, there is PostEmployee method which is responsible to get data from the user and map it to the data layer. In our case, it is Employee.cs file under Data folder. For understanding purposes, I didn’t connect to any database and am just returning whatever the user is sending. What we do here is we just map it from Dto to Data and vice versa.
 
We are receiving user sent data with the help of EmployeeDto.cs file and mapping that to the Employee.cs file.
 
In order to map data between these files, we need to add MappingProfile.cs to our project and keep the below code snippet inside it.
  1. using AutoMapper;  
  2. using AutoMapperExample.Controllers;  
  3. using AutoMapperExample.Data;  
  4. namespace AutoMapperExample {  
  5.     public class MappingProfile: Profile {  
  6.         public MappingProfile() {  
  7.             CreateMap < EmployeeDto, Employee > ();  
  8.             CreateMap < Employee, EmployeeDto > ();  
  9.         }  
  10.     }  
  11. }  
After that, we need to configure this file at ConfigureServices() method under Startup.cs file like below.
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     // Auto Mapper Configurations  
  3.     var mappingConfig = new MapperConfiguration(mc => {  
  4.         mc.AddProfile(new MappingProfile());  
  5.     });  
  6.     IMapper mapper = mappingConfig.CreateMapper();  
  7.     services.AddSingleton(mapper);  
  8.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  9. }  
Now, run the application and try to post data into Employee controller PostEmployee method.
 
In order to send the data, I’m using Postman.
 
How To Ignore Null Values In AutoMapper
 
We can see that whatever we send to the controller, it is returning as expected. So far, it is good.
 
Let us see the actual problem now. What if I send null property to this model?
 
Let me make the mobile property null and see the response.
 
How To Ignore Null Values In AutoMapper
 
If you observe here, the null property is returning in response. So, the solution to avoid null properties in response is add a piece of code inside ConfigureServices method of Startup.cs file like below.
  1. .AddJsonOptions(options => options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);  
Now, your complete configureServices() method looks like below.
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     // Auto Mapper Configurations  
  3.     var mappingConfig = new MapperConfiguration(mc => {  
  4.         mc.AddProfile(new MappingProfile());  
  5.     });  
  6.     IMapper mapper = mappingConfig.CreateMapper();  
  7.     services.AddSingleton(mapper);  
  8.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore);  
  9. }  
Now, send the same payload through Postman and see results. This time, you won’t see null property in response. In our case, the mobile property won’t appear this time.
 
How To Ignore Null Values In AutoMapper
 
Even though we send null value from the request body, it won’t appear in response result. This is how we can avoid null properties from the response with the help of Jsonserializersettings.
 
Hope you like this. Keep coding…….