Basically I have this class which represents 1:1 with my database
public class User
{
public int UserID { get; set; }
public string Username { get; set; }
public string Role { get; set; }
}
and I have this viewmodel
public class UserEditViewModel
{
public UserEditViewModel()
{
Roles = new List<string>();
}
public int UserID { get; set; }
[Required]
public string Username { get; set; }
[Required]
public List<string> Roles { get; set; }
}
I have no idea how to map between these 2. My current setup :
Mapper.CreateMap<UserEditViewModel, User>().ReverseMap();
Mapster is an emerging alternative to AutoMapper which was first published in 2015 and has over 7.4 million NuGet package downloads.
AutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
There is something similar to your questiong here, please can you check this out AutoMapper: Collection to Single string Property
PS: This is an example for mapping collection to single string property probably your example should look like below;
Mapper.CreateMap<User, UserEditViewModel>()
.ForMember(dest => dest.Roles,
m => m.MapFrom(src => src.Role.Split(',').ToList()));
And mapping the instances like below;
User myUser = new User();
myUser.Role = "r1,r2,r3,r4,r5";
myUser.UserID = 1;
myUser.Username = "MyUserName";
UserEditViewModel result = Mapper.Map<UserEditViewModel>(myUser);
2020 Edit: Since Expression.Call
API does not support optional parameter and you should Replace src.Role.Split(',')
with src.Role.Split(',', System.StringSplitOptions.None)
or src.Role.Split(',', System.StringSplitOptions.RemoveEmptyEntries)
To map a string to a collection Cihan Uygun's answer works, only to fix the error
CS0854 An expression tree may not contain a call or invocation that uses optional arguments
which is caused in later updates you should Replace src.Role.Split(',')
with src.Role.Split(',', System.StringSplitOptions.None)
or src.Role.Split(',', System.StringSplitOptions.RemoveEmptyEntries)
To do the reverse mapping just use src => string.Join(',', src.Roles)
Source for the error fix: https://newbedev.com/mapping-string-to-list-string-and-vice-versa-using-automapper
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With