Debugging an AutoMapper profile

I have an ASP.NET Core web app that uses AutoMapper in the minimal API endpoints to convert between database entities and DTOs. Nothing particularly fancy going on, all be working for a while.

For some reason, I suddenly started getting an exception when the mapper was called. The message was fairly unhelpful…

Error mapping types

Mapping types:
Order -> OrderDto
MyProject.Server.Data.Models.Order -> MyProject.Common.Models.Dtos+OrderDto

Type Map configuration:
Order -> OrderDto
MyProject.Server.Data.Models.Order -> MyProject.Common.Models.Dtos+OrderDto

Destination Member:
OrderItems

Doesn’t actually tell me what was going wrong, and as these maps have been working for a while, I was a bit stuck.

Probably obvious to those who read the docs 😎, but you can assert that your mapping is configured correctly, which gives more information.

In the server project’s Program.cs add the following code…

MapperConfiguration config = new(cfg => {
  cfg.AddProfile<AutoMapperProfile>();
});
config.AssertConfigurationIsValid();

When you next start your app, you’ll see loads of information filling up the console. If your mapping are all OK, then you will see a message for each type being mapped, along with a list of unmapped properties.

However, if you have any issues with the configuration, you’ll see those here.

In my case, I had a duplicate line in the profile. Deleting that fixed the issue. Now that would be fine, except that in my case, the line in question had been there for months, and the mapping had been working without problem. Why it suddenly noticed the problem now, and then report the issue on a completely different pair of types in beyond me!

Be First to Comment

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.