-
Hello, Currently working on a project and benchmarking Mapperly as a replacement to our current mapper library. The MapProperty is extremely simple and useful when we need to map some properties with different names. But i need to run some custom logic to fill a given property, and also keep the automatic source generated mappings. Something like, mapping from "DeclaredName" to "ShortDeclaredName", where i need some space to code how to fill the given property. I was able to make it work using [UseStaticMapper] and wrapping a private mapper inside a custom Map: [Mapper]
[UseStaticMapper(typeof(LeagueNameMapper))]
public static partial class TeamMapper
{
public static partial ViewModel.Team MapTeam(Team team);
public static partial ICollection<ViewModel.Team> MapTeams(ICollection<Team> teams);
[MapProperty(nameof(Player.Nickname), nameof(ViewModel.Player.CallerName))]
private static partial ViewModel.Player PrivateMapPlayer(Player player);
}
[Mapper]
public static partial class LeagueNameMapper
{
private static partial ViewModel.LeagueName PrivateMapLeagueName(LeagueName leagueName);
public static ViewModel.LeagueName MapLeagueName(LeagueName leagueName)
{
var viewmodel = PrivateMapLeagueName(leagueName);
viewmodel.ShortDeclaredName = viewmodel.DeclaredName[..3].ToUpper();
return viewmodel;
}
} I'm not a big fan of running logic in the mappings, however the code base is using this a lot, since it relies on "MapFrom" from automapper. Is there a cleaner way to do this custom logic? Thanks for the incredible library. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi diedona Mapperly is excelent tool in such cases. Take a look: https://mapperly.riok.app/docs/configuration/before-after-map/ |
Beta Was this translation helpful? Give feedback.
-
As mentioned by @ichalyshev the Mapperly way to address this is by using before/after map code. You can do it in a separate mapper with |
Beta Was this translation helpful? Give feedback.
As mentioned by @ichalyshev the Mapperly way to address this is by using before/after map code. You can do it in a separate mapper with
UseStaticMapper
, but you can also do it directly in the same mapper, doesn't matter to Mapperly.IMO this is pretty clean/good readable code.
If you need to apply the same modification to several properties, #783 will come to help (not yet implemented).