[英]Automapper mapping to multiple foreign keys
我正在使用包含用戶詳細信息的頁面列表。 除了我從UserRole表中獲取ID的角色(我使用它從角色表中獲取Roles)之外,所有詳細信息都來自User表。 一個用戶可能有多個角色。 因此,基本上,UserRole表具有UserID和RoleID作為連接User和Role表的外鍵。
所以我的代碼是
config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<User, UserViewModel>().ForMember(m => m.RolesList, opt => opt.MapFrom(source => (source.UserRoles.Select(w=>w.Role.Name).ToList())));
});
RolesList是一個IEnumerable。
在有多個外鍵的情況下,我該如何處理?
編輯:修改后的代碼現在提供了角色,但是在用戶具有多個角色的情況下,它仍然只提供了一個角色。 有沒有一種方法可以獲取特定用戶的所有角色?
我可以使用普通的Linq查詢找到解決方案。
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()));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.