feat: Automatically use ref target property mappings#2242
feat: Automatically use ref target property mappings#2242juliancarrivick wants to merge 1 commit intoriok:mainfrom
Conversation
… for property mapping When a user defines a void mapping method with a `ref` target parameter, Mapperly now automatically uses it for property-level mappings of those types, without requiring explicit `[MapProperty(Use = nameof(...))]` opt-in. A new-instance user mapping for the same types still takes precedence, and same-type mappings are excluded to avoid shadowing direct assignment. A method decorated with `[UseMapper]`/`Default = true` overrides this precedence. Adds `HasExistingTargetRefUserMapping` on `MappingBuilderContext` and an `IsRefTarget` property on `UserImplementedExistingTargetMethodMapping`.
|
Thank you for this contribution! I'll look into this the coming week. |
|
I agree that some solution would be good. I tried generic mappings from https://next.mapperly.riok.app/docs/configuration/generic-mapping/ and explicit method mappings. The current implementation does not support either (without being explicit with MapProperty). If needed I can give examples. But in this case #276 would probably be the better implementation. |
Automatically use ref target property mappings
Description
This was motivated by wanting to switch from Automapper, where I was able to conditionally update a value based on whether a custom
Optionalclass had a value or not. With Mapperly this requires a ref target mapping, however they currently have to be explicitly opted into for every field on the object, which doesn't scale very well. e.g. When you have many DTOs with many properties that need such a mapping from a controller type to the DB entity type. It seemed timely to implement this functionality since 5.0 is in pre-release at the moment.As a disclosure, I used Claude to generate the initially failing test cases and inspected that they were reasonable, adapting them to use the pre-existing test models. I also used it to generate the initial fix and also adapted that to the existing conventions.
I'm not entirely happy with the fix, it seems to duplicate checks that are performed elsewhere too (e.g. default checking) and having to downcast to see if it is a ref target or not. I investigated doing some refactoring in this space but it got very messy very quickly so I figured that would be better performed by someone more familiar with the code base.
Thank you for this great project, I hope to be able to use it with this change soon!
Checklist