Skip to content

Instantly share code, notes, and snippets.

@StabbyCutyou
Last active April 15, 2021 20:02
Show Gist options
  • Save StabbyCutyou/c5fedecf81a824287d55a8ae54f086ba to your computer and use it in GitHub Desktop.
Save StabbyCutyou/c5fedecf81a824287d55a8ae54f086ba to your computer and use it in GitHub Desktop.
// What we originally had
namespace Example
{
public class UserMapProfile : Profile
{
public UserMapProfile()
{
CreateMap<ExternalUser, InternalUser>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Profile.DisplayName))
}
}
}
// What we wound up doing
namespace Example
{
public class UserMapProfile : Profile
{
public UserMapProfile()
{
CreateMap<ExternalUser, InternalUser>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Profile.DisplayName))
.AfterMap((src, dest) => dest.Name = src.Profile.Name);
}
}
}
namespace Example
{
// This is a model representing something in our system
public class InternalUser {
public string Name {get; set;}
}
// This models part of a datamodel from a third party api
public class ExternalUserProfile {
public string Name {get; set;} // This field is always set
}
// This models a datamodel from a third party api
public class ExternalUser {
// This field is only sometimes set - we cannot control nor influence nor predict this
// We also find it confusing and frustrating that this particular API returns names in 2 places
// and seemingly only one of them is reliably provided each time, but is out of our control.
public string Name {get;set;}
public ExternalUserProfile Profile {get;set;}
}
}
namespace Example
{
public class UserService()
{
public IEnumerable<InternalUser> GetUsersFromThirdParty() {
var 3pusers = LoadUsersFromThirdParty()
// mapper.Map is going to see that ExternalUser and InternalUser both have a Name attribute
// It is not going to actually use the override mapping in the UserMapProfile. It appears to find
// the 1:1 mapping between fields, and ignore what we set in mapconfig_original.
// In order to use the behavior we want, we must rely on AfterMap, as done in mapconfig_updated
return mapper.Map<IEnumerable<ExternalUser>, IEnumerable<InternalUser>>(3pUsers)
}
public IEnumerable<ExternalUser> LoadUsersFromThirdParty() {
// imagine that this hits a rest api, gets back json, and hydrates it into a list of ExternalUsers
// I've cut all that code out for the sake of brevity as it doesn't impact how automapper behaves.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment