CodexBloom - Programming Q&A Platform

Unexpected Null Reference Exception When Using AutoMapper with Nested Collections in .NET 5

👀 Views: 2 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
C# AutoMapper .NET 5

I'm deploying to production and I'm working on a project and hit a roadblock. I'm encountering a `NullReferenceException` when trying to map a source object that contains nested collections to a destination object using AutoMapper in .NET 5. The source object has a collection of child objects, and one of the properties within those child objects is sometimes null. Here's a simplified version of my models: ```csharp public class Parent { public string Name { get; set; } public List<Child> Children { get; set; } } public class Child { public string Name { get; set; } public string Description { get; set; } } public class ParentDto { public string Name { get; set; } public List<ChildDto> Children { get; set; } } public class ChildDto { public string Name { get; set; } public string Description { get; set; } } ``` I configured AutoMapper like this: ```csharp var config = new MapperConfiguration(cfg => { cfg.CreateMap<Parent, ParentDto>(); cfg.CreateMap<Child, ChildDto>(); }); var mapper = config.CreateMapper(); ``` When I call the mapping function: ```csharp var parent = new Parent { Name = "John", Children = new List<Child> { new Child { Name = "Child1", Description = null }, new Child { Name = "Child2", Description = "Description2" } } }; var parentDto = mapper.Map<ParentDto>(parent); ``` I get the following exception: ``` Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object. ``` I've tried adding null checks in my mapping configuration using `ForMember`, but that doesn't seem to resolve the issue. ```csharp cfg.CreateMap<Child, ChildDto>() .ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description ?? "No description available")); ``` I expected the mapping to handle the null `Description` gracefully, but it seems like the issue lies somewhere in the nested collection handling. Has anyone faced a similar problem, or does anyone have suggestions on how to handle nested collections with potential null values in AutoMapper? I'm working on a service that needs to handle this. I recently upgraded to C# latest. Any pointers in the right direction?