我有這個異常,當我試圖從一個對象映射到另一個。AutoMapper - AutoMapper.AutoMapperMappingException
在我的global.asax.cs我得到這個:
RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new AppContext()));
Mapper.Initialize(cfg =>
{
cfg.CreateMap<AppUser, TokenAuthorizationModel>()
.ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.UserName))
.ForMember(dest => dest.Role, opt => opt.MapFrom(src => roleManager.FindById(src.Roles.First().RoleId).Name));
});
而且我得到了這個AutoMapper.AutoMapperMappingException例外,我登錄控制器上,especifically在這條線:
TokenAuthorizationModel tokenClaims = Mapper.Map<TokenAuthorizationModel>(validUser);
這些都是我的模型:
public class AppUser : IdentityUser
{
public virtual List<CourseModel> Courses { get; set; }
public string FullName { get; set; }
public int Reputation { get; set; }
}
和目標:
public class TokenAuthorizationModel
{
public string UserName { get; set; }
public string Role { get; set; }
}
有人能幫我一下嗎?提前致謝! :)
roleManager是否正在調用數據庫?如果是這樣,我肯定會避免在automapper中做類似的事情。 – axlj
但我需要,你還有什麼其他的方式呢?因爲我需要獲取數據庫中用戶的角色。 – RottenCheese
'用戶'有'角色'權利?所以如果你在這裏需要角色,在查找用戶時應該急於加載角色。 – axlj