CodexBloom - Programming Q&A Platform

InvalidOperationException When Using AutoMapper with Nested Collections in .NET 6

πŸ‘€ Views: 31 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-17
automapper dotnet-6 mappings csharp

I recently switched to I'm working on a project and hit a roadblock. I'm working on a personal project and I'm currently working with an `InvalidOperationException` when trying to map nested collections using AutoMapper in my .NET 6 application. I've defined a source and destination class that involves a parent-child relationship, but the mapping seems to unexpected result under certain conditions. The source class looks like this: ```csharp public class Parent { public int Id { get; set; } public string Name { get; set; } public List<Child> Children { get; set; } } public class Child { public int Id { get; set; } public string ChildName { get; set; } } ``` And the destination classes are: ```csharp public class ParentDto { public int Id { get; set; } public string Name { get; set; } public List<ChildDto> Children { get; set; } } public class ChildDto { public int Id { get; set; } public string ChildName { get; set; } } ``` I configured the mapping like this: ```csharp var config = new MapperConfiguration(cfg => { cfg.CreateMap<Parent, ParentDto>(); cfg.CreateMap<Child, ChildDto>(); }); var mapper = config.CreateMapper(); ``` However, when I try to map a `Parent` object that has a list of `Child` objects, I get the following exception: ``` InvalidOperationException: The source type Parent does not have a property named Children. ``` I've verified that my source object is not null and contains the expected properties. I also checked the casing and naming of the properties to ensure there are no discrepancies. This behavior only occurs if the `Children` collection is empty or null. I've tried initializing the `Children` property in the `Parent` class to an empty list in the constructor, but that didn't resolve the scenario. Here’s how I’m mapping it: ```csharp var parent = new Parent { Id = 1, Name = "Parent1", Children = null }; var parentDto = mapper.Map<ParentDto>(parent); ``` This should ideally return a `ParentDto` with the `Children` property set to an empty list or null. Any insights on why this might be happening or how to properly handle mapping nested collections in this scenario would be greatly appreciated! My development environment is Windows. For context: I'm using Csharp on macOS. What would be the recommended way to handle this? The project is a CLI tool built with Csharp. What's the best practice here?