我有来自 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 来做到这一点。请问你能帮我吗?
谢谢你
不需要
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()));