CodexBloom - Programming Q&A Platform

Dapper Not Mapping Complex Types Correctly in .NET 6 - How to Fix It?

👀 Views: 33 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
dapper .net-6 c# C#

I'm refactoring my project and I'm wondering if anyone has experience with I've been researching this but I'm trying to figure out I've been struggling with this for a few days now and could really use some help..... I'm facing an issue with Dapper not correctly mapping a complex object when querying from my SQL Server database. I have a class structure like this: ```csharp public class Order { public int OrderId { get; set; } public Customer Customer { get; set; } } public class Customer { public int CustomerId { get; set; } public string Name { get; set; } } ``` I execute the following query, trying to load the `Order` along with its associated `Customer`: ```csharp var sql = "SELECT o.OrderId, c.CustomerId, c.Name FROM Orders o JOIN Customers c ON o.CustomerId = c.CustomerId"; var orders = await db.QueryAsync<Order, Customer, Order>(sql, (order, customer) => { order.Customer = customer; return order; }); ``` However, the `Customer` property of the `Order` instances is coming out as `null`. When testing the SQL query directly in SQL Server Management Studio, it returns valid results, so I suspect it might be a mapping issue. I have tried using the `SplitOn` parameter, but it doesn't seem to make a difference: ```csharp var orders = await db.QueryAsync<Order, Customer, Order>( sql, (order, customer) => { order.Customer = customer; return order; }, splitOn: "CustomerId" ); ``` The Dapper version I'm using is 2.0.90, and I'm running .NET 6. I checked the documentation, but it doesn't provide much help for complex nested types. What could I be missing here? Is there a specific configuration or pattern I should be following to ensure proper mapping with Dapper? I'm working on a CLI tool that needs to handle this. I'd really appreciate any guidance on this. The project is a CLI tool built with C#. Any pointers in the right direction? Thanks in advance! I've been using C# for about a year now. Am I missing something obvious? This issue appeared after updating to C# LTS. Any advice would be much appreciated.