CodexBloom - Programming Q&A Platform

Issues with AutoMapper Mapping Nested Collections in C# 9 - Empty Destination List

๐Ÿ‘€ Views: 57 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-08
c# automapper dotnet collections C#

I've been researching this but I'm experiencing an issue with AutoMapper when trying to map a source object that has a nested collection to a destination object. The source object looks like this: ```csharp public class Author { public string Name { get; set; } public List<Book> Books { get; set; } } public class Book { public string Title { get; set; } public int Year { get; set; } } public class AuthorDto { public string Name { get; set; } public List<BookDto> Books { get; set; } } public class BookDto { public string Title { get; set; } public int Year { get; set; } } ``` I have set up my AutoMapper configuration like this: ```csharp var config = new MapperConfiguration(cfg => { cfg.CreateMap<Author, AuthorDto>(); cfg.CreateMap<Book, BookDto>(); }); var mapper = config.CreateMapper(); ``` However, when I try to map an `Author` object that has a list of `Book` objects, the `Books` list in the `AuthorDto` comes out empty. Hereโ€™s how Iโ€™m doing the mapping: ```csharp var author = new Author { Name = "John Doe", Books = new List<Book> { new Book { Title = "C# in Depth", Year = 2021 }, new Book { Title = "Clean Code", Year = 2018 } } }; var authorDto = mapper.Map<AuthorDto>(author); ``` Despite the source `Author` object being correctly populated, the `authorDto.Books` ends up as an empty list. Iโ€™ve verified that the `Books` collection in the `Author` is not null or empty before mapping. Iโ€™ve also tried using `.ToList()` on the Books property in the configuration, but that didn't resolve the issue. Does anyone have insights on why the mapping is not correctly populating the nested collection? Is there a specific configuration Iโ€™m missing in AutoMapper that could cause this behavior? Iโ€™m using AutoMapper version 10.1.1 with .NET 5.0, and Iโ€™ve ensured all the necessary namespaces are included. Any help would be greatly appreciated! This issue appeared after updating to C# 3.9. Thanks for any help you can provide!