集合中的 C# Automapper AfterMap 属性

问题描述 投票:0回答:1

我有来自 AspNet Core 身份的用户对象列表:

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; }
    ......

}

我应该将此列表映射到 UserLite 对象列表

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; }
}

但是,UserLite 对象有一个属性 IsExternalProviderUser,必须根据示例中所示的条件进行映射:

var userLiteList = usersList.Select(user => new UserLite
{
    Email = user.Email,
    Id = user.Id,
    Name = user.Name,
    Surname = GetSurname();  
        
}).ToList(); // This is the condition for mapping the property

一开始我没有这个属性,所以我使用了automapper和经典方法:

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

但现在我不知道如何设置 AfterMap 来做到这一点。请问你能帮我吗?
谢谢你

c# .net-core automapper
1个回答
2
投票

不需要

AfterMap
,只需使用
ForMember

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

或者您可以创建一个扩展方法来使代码更简洁。

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()));
© www.soinside.com 2019 - 2024. All rights reserved.