简体   繁体   中英

Automapper mapping to multiple foreign keys

I am using a paged list which has details of a user. All the details come from the User table except the role which I get ID from the UserRole table which I use it to get Roles from the role table. There is a chance of one user having multiple roles. So basically the UserRole table has UserID and RoleID as foreign keys which connect the User and Role table.

So the code that I have is

config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<User, UserViewModel>().ForMember(m => m.RolesList, opt => opt.MapFrom(source => (source.UserRoles.Select(w=>w.Role.Name).ToList())));
                });

The RolesList is an IEnumerable.

How do i go about in this case of multiple foreign keys?

EDIT: The modified code now gives the role but in case of a user with multiple roles, It still gives me only one role. Is there a way I can get all the roles for a particular user?

I was able to find a solution by using normal Linq Query.

config = new MapperConfiguration(cfg =>
                {
                    cfg.CreateMap<User, UserViewModel>()
                       .ForMember(m => m.UserRolesList, opt => opt.MapFrom(source => source.UserRoles
                         .Where(w => w.UserId == source.Id)
                         .Select(w => w.Role.Name)
                         .ToList()));
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM