CodexBloom - Programming Q&A Platform

Intermittent NullReferenceException When Accessing Properties of a Complex Object in ASP.NET Core API with AutoMapper

👀 Views: 94 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
c# asp.net-core automapper C#

I'm relatively new to this, so bear with me. I'm facing an intermittent `NullReferenceException` when trying to access properties of a complex object that I've mapped using AutoMapper in my ASP.NET Core API. The issue occurs specifically when the mapped object is retrieved from a database and has related entities that can be null. I have a `User` entity that has a one-to-many relationship with the `Orders` entity. Here is the DTO and mapping configuration: ```csharp public class UserDto { public int Id { get; set; } public string Name { get; set; } public List<OrderDto> Orders { get; set; } } public class OrderDto { public int OrderId { get; set; } public string ProductName { get; set; } } var config = new MapperConfiguration(cfg => { cfg.CreateMap<User, UserDto>() .ForMember(dest => dest.Orders, opt => opt.MapFrom(src => src.Orders)); }); var mapper = config.CreateMapper(); ``` In my controller, I am trying to fetch a user and map it to `UserDto`: ```csharp [HttpGet("{id}")] public IActionResult GetUser(int id) { var user = _context.Users.Include(u => u.Orders).FirstOrDefault(u => u.Id == id); if (user == null) { return NotFound(); } var userDto = mapper.Map<UserDto>(user); return Ok(userDto); } ``` The exception occurs when the `Orders` collection is null, and I try to access `userDto.Orders`. I thought AutoMapper should handle this scenario gracefully, but it seems that's not the case. I tried adding a null check before mapping, like this: ```csharp if (user.Orders == null) { user.Orders = new List<Order>(); } ``` However, that doesn't seem to fix the issue entirely, as I'm still getting the `NullReferenceException` intermittently. I also checked that the collection should not be null based on how the data is seeded, but it seems there are race conditions leading to this. Has anyone faced a similar issue, or can suggest how to ensure that the mapped DTOs handle null collections correctly? I'm using .NET 6 and AutoMapper version 10.1.1. I'm developing on Debian with C#.