Home > Net >  C# Automapper AfterMap property in a collection
C# Automapper AfterMap property in a collection

Time:09-29

I have a list of User objects from AspNet Core identity:

public class User
{
    public Guid Id { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime? LastLoginDateTime { get; set; }
    public bool EmailConfirmed { get; set; }
    public ICollection<UserClaim> Claims { get; set; }
    public ICollection<UserLogin> Logins { get; set; }
    ......

}

and I should map this list to a list of UserLite objects

public class UserLite
{
    public Guid Id { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public DateTime? LastLoginDateTime { get; set; }
    public bool EmailConfirmed { get; set; }
    public bool IsExternalProviderUser { get; set; }
}

However, the UserLite object has a property, IsExternalProviderUser, that must be mapped according to a condition as shown in the example:

var userLiteList = usersList.Select(user => new UserLite
{
    Email = user.Email,
    Id = user.Id,
    Name = user.Name,
    Surname = user.Surname,
    EmailConfirmed = user.EmailConfirmed,
    LastLoginDateTime = user.LastLoginDateTime?.DateTime,
    IsExternalProviderUser = user.Logins.Any(login => !login.LoginProvider.Equals("Test", StringComparison.InvariantCultureIgnoreCase))
}).ToList(); // This is the condition for mapping the property

In the beginning I didn't have this property so I used automapper with the classic method:

_mapper.Map<List<UserLite>>(userList);

But now I don't know how to set up an AfterMap to do this. Kindly can you help me?
Thank you

CodePudding user response:

No need for AfterMap, simply use ForMember:

CreateMap<User, UserLite>()
    .ForMember(dest => dest.IsExternalProviderUser,
        opt => opt.MapFrom(src => src.Logins.Any(login => !login.LoginProvider.Equals("Test", StringComparison.InvariantCultureIgnoreCase))));

Or you can create an extension method to make the code a bit cleaner.

public static class Extensions
{
    public static bool IsExternalProviderUser(this User user)
    {
        return user.Logins.Any(login => !login.LoginProvider.Equals("Test", StringComparison.InvariantCultureIgnoreCase));
    }
}
CreateMap<User, UserLite>()
    .ForMember(dest => dest.IsExternalProviderUser,
        opt => opt.MapFrom(src => src.IsExternalProviderUser()));
  • Related